TIDE/backend/app/Post/EloquentPostRepository.php
yisroel e3dddc60aa
add Post persistence: model, migration, eloquent + fake repo
PostModel maps posts table (id, user_id fk, title, body text,
created_at indexed). EloquentPostRepository: create, find,
findByUserId (desc by created_at), findRecent (limit, desc),
delete - chain via ::query() to keep larastan happy.
FakePostRepository sorts on read (defensive copy each return).
cascade-on-delete on user_id so removing a user nukes their
posts.

phpstan.neon suppresses staticMethod.dynamicCall under
app/*/Eloquent*Repository.php - phpstan-strict-rules flags
Eloquent's fluent builder idiom (Model::query()->orderBy())
because the static methods become instance calls mid-chain.
suppression scoped to repo files only so the rule still
applies elsewhere.
2026-05-06 15:22:22 +03:00

83 lines
1.9 KiB
PHP

<?php
namespace App\Post;
use DateTimeImmutable;
use DateTimeZone;
class EloquentPostRepository implements PostRepository
{
public function create(CreatePostDto $dto): Post
{
$model = PostModel::create([
'user_id' => $dto->userId,
'title' => $dto->title,
'body' => $dto->body,
'created_at' => $dto->createdAt,
]);
return $this->toDomain($model);
}
public function find(int $id): ?Post
{
$model = PostModel::find($id);
return $model === null ? null : $this->toDomain($model);
}
/**
* @return Post[]
*/
public function findByUserId(int $userId): array
{
$models = PostModel::query()
->where('user_id', $userId)
->orderBy('created_at', 'desc')
->get();
return $models->map(
function (PostModel $model) {
return $this->toDomain($model);
},
)->all();
}
/**
* @return Post[]
*/
public function findRecent(int $limit): array
{
$models = PostModel::query()
->orderBy('created_at', 'desc')
->limit($limit)
->get();
return $models->map(
function (PostModel $model) {
return $this->toDomain($model);
},
)->all();
}
public function delete(int $id): void
{
PostModel::query()->where('id', $id)->delete();
}
private function toDomain(PostModel $model): Post
{
$utc = new DateTimeZone('UTC');
return new Post(
id: $model->id,
userId: $model->user_id,
title: $model->title,
body: $model->body,
createdAt: new DateTimeImmutable(
$model->created_at->toDateTimeString(),
$utc,
),
);
}
}