implement CreateComment use case
This commit is contained in:
parent
2557c9b6a9
commit
e8d2ff3fdf
2 changed files with 61 additions and 0 deletions
49
backend/app/Comment/UseCases/CreateComment/CreateComment.php
Normal file
49
backend/app/Comment/UseCases/CreateComment/CreateComment.php
Normal file
|
|
@ -0,0 +1,49 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Comment\UseCases\CreateComment;
|
||||||
|
|
||||||
|
use App\Auth\Clock;
|
||||||
|
use App\Comment\Comment;
|
||||||
|
use App\Comment\CommentRepository;
|
||||||
|
use App\Comment\CreateCommentDto;
|
||||||
|
use App\Exceptions\BadRequestException;
|
||||||
|
use App\Post\PostRepository;
|
||||||
|
use DomainException;
|
||||||
|
|
||||||
|
class CreateComment
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private CommentRepository $commentRepo,
|
||||||
|
private PostRepository $postRepo,
|
||||||
|
private Clock $clock,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws BadRequestException
|
||||||
|
* @throws DomainException
|
||||||
|
*/
|
||||||
|
public function execute(CreateCommentRequest $request): Comment
|
||||||
|
{
|
||||||
|
if ($request->postId <= 0) {
|
||||||
|
throw new BadRequestException('postId must be positive');
|
||||||
|
}
|
||||||
|
if ($request->userId <= 0) {
|
||||||
|
throw new BadRequestException('userId must be positive');
|
||||||
|
}
|
||||||
|
$body = $request->body === null ? '' : trim($request->body);
|
||||||
|
if ($body === '') {
|
||||||
|
throw new BadRequestException('body is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->postRepo->find($request->postId) === null) {
|
||||||
|
throw new DomainException('post not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->commentRepo->create(new CreateCommentDto(
|
||||||
|
postId: $request->postId,
|
||||||
|
userId: $request->userId,
|
||||||
|
body: $body,
|
||||||
|
createdAt: $this->clock->now(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Comment\UseCases\CreateComment;
|
||||||
|
|
||||||
|
class CreateCommentRequest
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public int $postId,
|
||||||
|
public int $userId,
|
||||||
|
public ?string $body,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue