TIDE/backend/app/Comment/EloquentCommentRepository.php

66 lines
1.5 KiB
PHP

<?php
namespace App\Comment;
use DateTimeImmutable;
use DateTimeZone;
class EloquentCommentRepository implements CommentRepository
{
public function create(CreateCommentDto $dto): Comment
{
$model = CommentModel::create([
'post_id' => $dto->postId,
'user_id' => $dto->userId,
'body' => $dto->body,
'created_at' => $dto->createdAt,
]);
return $this->toDomain($model);
}
public function find(int $id): ?Comment
{
$model = CommentModel::find($id);
return $model === null ? null : $this->toDomain($model);
}
/**
* @return Comment[]
*/
public function findByPostId(int $postId): array
{
$models = CommentModel::query()
->where('post_id', $postId)
->orderBy('created_at', 'asc')
->get();
return $models->map(
function (CommentModel $model) {
return $this->toDomain($model);
},
)->all();
}
public function delete(int $id): void
{
CommentModel::query()->where('id', $id)->delete();
}
private function toDomain(CommentModel $model): Comment
{
$utc = new DateTimeZone('UTC');
return new Comment(
id: $model->id,
postId: $model->post_id,
userId: $model->user_id,
body: $model->body,
createdAt: new DateTimeImmutable(
$model->created_at->toDateTimeString(),
$utc,
),
);
}
}