67 lines
1.7 KiB
PHP
67 lines
1.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Repositories;
|
|
|
|
use Medoo\Medoo;
|
|
use App\Models\Post;
|
|
|
|
final class PostRepository
|
|
{
|
|
public function __construct(private Medoo $db)
|
|
{
|
|
}
|
|
|
|
public function findAll(): array
|
|
{
|
|
$rows = $this->db->select('post', '*', ['ORDER' => ['id' => 'DESC']]);
|
|
return array_map(fn ($row) => Post::fromArray($row), $rows ?: []);
|
|
}
|
|
|
|
public function findBySlug(string $slug): ?Post
|
|
{
|
|
$row = $this->db->get('post', '*', ['slug' => $slug]);
|
|
return $row ? Post::fromArray($row) : null;
|
|
}
|
|
|
|
public function findById(int $id): ?Post
|
|
{
|
|
$row = $this->db->get('post', '*', ['id' => $id]);
|
|
return $row ? Post::fromArray($row) : null;
|
|
}
|
|
|
|
public function create(Post $post, string $slug): int
|
|
{
|
|
$this->db->insert('post', [
|
|
'title' => $post->getTitle(),
|
|
'content' => $post->getContent(),
|
|
'slug' => $slug,
|
|
'created_at' => date('Y-m-d H:i:s'),
|
|
'updated_at' => date('Y-m-d H:i:s'),
|
|
]);
|
|
return (int) $this->db->id();
|
|
}
|
|
|
|
public function update(int $id, Post $post, string $slug): void
|
|
{
|
|
$this->db->update('post', [
|
|
'title' => $post->getTitle(),
|
|
'content' => $post->getContent(),
|
|
'slug' => $slug,
|
|
'updated_at' => date('Y-m-d H:i:s'),
|
|
], ['id' => $id]);
|
|
}
|
|
|
|
public function delete(int $id): void
|
|
{
|
|
$this->db->delete('post', ['id' => $id]);
|
|
}
|
|
|
|
public function slugExists(string $slug, ?int $excludeId = null): bool
|
|
{
|
|
$existing = $this->db->get('post', 'id', ['slug' => $slug]);
|
|
return $existing && (!$excludeId || $existing !== $excludeId);
|
|
}
|
|
}
|