83 lines
2.1 KiB
PHP
Raw Permalink Normal View History

2025-01-23 00:19:07 +01:00
<?php
declare(strict_types=1);
namespace App\Services\Comment;
use App\Models\Comment;
use App\Models\Post;
use App\Services\PaginableResource;
use App\Services\QueryRequestModifiers\Comment\CommentFilter;
use App\Services\QueryRequestModifiers\Comment\CommentFilterDTO;
use App\Services\QueryRequestModifiers\Comment\CommentOrder;
use App\Services\QueryRequestModifiers\Comment\CommentOrderDTO;
class PostCommentService implements CommentServiceInterface
{
public function __construct(
protected readonly CommentFilter $commentFilter,
protected readonly CommentOrder $commentOrder,
protected readonly int $paginate = 10,
) {
}
public function fetchComments(int $remoteId, int $page, ?CommentFilterDTO $filters, ?CommentOrderDTO $orderDef): PaginableResource
{
$post = Post::findOrFail($remoteId);
$comments = $this->commentOrder->apply(
$this->commentFilter->apply($post->comments()->getQuery(), $filters),
$orderDef
)->paginate($this->paginate);
return PaginableResource::createFromLengthAwarePaginator($comments);
}
public function storeComment(array $data, int $postId): ?Comment
{
$post = Post::findOrFail($postId);
$comment = $post->comments()->create([
'content' => $data['content'],
]);
return Comment::findOrFail($comment->id);
}
public function deleteComment(int $remoteId, int $id): bool
{
$post = Post::find($remoteId);
if ($post === null) {
return false;
}
$comment = $post->comments()->find($id);
if ($comment === null) {
return false;
}
return $comment->delete();
}
public function updateComment(array $data, int $remoteId, int $id): ?Comment
{
$post = Post::find($remoteId);
if ($post === null) {
return null;
}
$comment = $post->comments()->find($id);
if ($comment === null) {
return null;
}
$comment->update($data);
return Comment::findOrFail($comment->id);
}
}