add Comment persistence: model, migration, eloquent + fake repo

This commit is contained in:
Yisroel Baum 2026-05-06 22:14:11 +03:00
parent 0d589340d9
commit 93da08756c
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
4 changed files with 219 additions and 0 deletions

View file

@ -0,0 +1,82 @@
<?php
namespace Tests\Fakes;
use App\Comment\Comment;
use App\Comment\CommentRepository;
use App\Comment\CreateCommentDto;
class FakeCommentRepository implements CommentRepository
{
/**
* @var Comment[]
*/
private array $existingComments = [];
public function create(CreateCommentDto $dto): Comment
{
$id = $this->getNextId();
$comment = new Comment(
id: $id,
postId: $dto->postId,
userId: $dto->userId,
body: $dto->body,
createdAt: $dto->createdAt,
);
$this->existingComments[$id] = $comment;
return $this->copy($comment);
}
public function find(int $id): ?Comment
{
$comment = $this->existingComments[$id] ?? null;
if ($comment === null) {
return null;
}
return $this->copy($comment);
}
/**
* @return Comment[]
*/
public function findByPostId(int $postId): array
{
$matching = [];
foreach ($this->existingComments as $comment) {
if ($comment->getPostId() === $postId) {
$matching[] = $this->copy($comment);
}
}
usort(
$matching,
function (Comment $left, Comment $right) {
return $left->getCreatedAt() <=> $right->getCreatedAt();
},
);
return $matching;
}
public function delete(int $id): void
{
unset($this->existingComments[$id]);
}
private function copy(Comment $comment): Comment
{
return new Comment(
id: $comment->getId(),
postId: $comment->getPostId(),
userId: $comment->getUserId(),
body: $comment->getBody(),
createdAt: $comment->getCreatedAt(),
);
}
private function getNextId(): int
{
return count($this->existingComments) + 1;
}
}