add Comment persistence: model, migration, eloquent + fake repo
This commit is contained in:
parent
0d589340d9
commit
93da08756c
4 changed files with 219 additions and 0 deletions
82
backend/tests/Fakes/FakeCommentRepository.php
Normal file
82
backend/tests/Fakes/FakeCommentRepository.php
Normal 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;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue