49 lines
1.3 KiB
PHP
49 lines
1.3 KiB
PHP
<?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(),
|
|
));
|
|
}
|
|
}
|