107 lines
2.5 KiB
PHP
107 lines
2.5 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services\Post;
|
|
|
|
use App\Models\Post;
|
|
use App\Models\Tag;
|
|
use App\Services\PaginableResource;
|
|
use App\Services\QueryRequestModifiers\Post\PostFilter;
|
|
use App\Services\QueryRequestModifiers\Post\PostFilterDTO;
|
|
use App\Services\QueryRequestModifiers\Post\PostOrder;
|
|
use App\Services\QueryRequestModifiers\Post\PostOrderDTO;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class PostService implements PostServiceInterface
|
|
{
|
|
public function __construct(
|
|
protected readonly PostFilter $postFilter,
|
|
protected readonly PostOrder $postOrder,
|
|
protected readonly int $paginate = 10,
|
|
) {
|
|
}
|
|
|
|
public function fetchPosts(int $page, ?PostFilterDTO $filters, ?PostOrderDTO $orderDef): PaginableResource
|
|
{
|
|
$posts = $this->postOrder->apply(
|
|
$this->postFilter->apply(Post::with(['category', 'tags', 'comments']), $filters),
|
|
$orderDef
|
|
)->paginate($this->paginate, page: $page);
|
|
return PaginableResource::createFromLengthAwarePaginator($posts);
|
|
}
|
|
|
|
public function findPost(int $id): ?Post
|
|
{
|
|
return Post::with(['category', 'tags', 'comments'])->find($id);
|
|
}
|
|
|
|
public function storePost(array $data): Post
|
|
{
|
|
DB::beginTransaction();
|
|
|
|
$post = Post::create($data);
|
|
|
|
if (isset($data['tags'])) {
|
|
$tags = [];
|
|
|
|
foreach ($data['tags'] as $tag) {
|
|
$tag = Tag::firstOrCreate(['name' => $tag]);
|
|
$tags[] = $tag;
|
|
}
|
|
|
|
$post->tags()->sync($tags);
|
|
}
|
|
|
|
$post = $this->findPost($post->id);
|
|
|
|
if ($post === null) {
|
|
throw new \InvalidArgumentException('This should never happen - post is null');
|
|
}
|
|
|
|
DB::commit();
|
|
|
|
return $post;
|
|
}
|
|
|
|
public function updatePost(array $data, int $id): ?Post
|
|
{
|
|
DB::beginTransaction();
|
|
|
|
$post = Post::find($id);
|
|
|
|
if ($post === null) {
|
|
return null;
|
|
}
|
|
|
|
if (isset($data['tags'])) {
|
|
$tags = [];
|
|
|
|
foreach ($data['tags'] as $tag) {
|
|
$tag = Tag::firstOrCreate(['name' => $tag]);
|
|
$tags[] = $tag;
|
|
}
|
|
|
|
$post->tags()->sync($tags);
|
|
}
|
|
|
|
$post->update($data);
|
|
|
|
DB::commit();
|
|
|
|
return $this->findPost($post->id);
|
|
}
|
|
|
|
public function deletePost(int $id): bool
|
|
{
|
|
$post = Post::find($id);
|
|
|
|
if ($post === null) {
|
|
return false;
|
|
}
|
|
|
|
$post->delete();
|
|
return true;
|
|
}
|
|
}
|