implement CreateComment use case

This commit is contained in:
Yisroel Baum 2026-05-06 22:14:55 +03:00
parent 2557c9b6a9
commit e8d2ff3fdf
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
2 changed files with 61 additions and 0 deletions

View 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(),
));
}
}

View file

@ -0,0 +1,12 @@
<?php
namespace App\Comment\UseCases\CreateComment;
class CreateCommentRequest
{
public function __construct(
public int $postId,
public int $userId,
public ?string $body,
) {}
}