Added slug db column
This commit is contained in:
@@ -37,23 +37,14 @@ class PostController
|
||||
{
|
||||
$slug = (string)($args['slug'] ?? '');
|
||||
|
||||
// Récupérer tous les posts et chercher celui qui correspond au slug
|
||||
$rows = $this->db->select('post', '*', ['ORDER' => ['id' => 'DESC']]);
|
||||
$post = null;
|
||||
$row = $this->db->get('post', '*', ['slug' => $slug]);
|
||||
|
||||
foreach ($rows ?: [] as $row) {
|
||||
$postObj = Post::fromArray($row);
|
||||
if ($postObj->getSlug() === $slug) {
|
||||
$post = $postObj;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$post) {
|
||||
if (!$row) {
|
||||
$res->getBody()->write('Article non trouvé');
|
||||
return $res->withStatus(404);
|
||||
}
|
||||
|
||||
$post = Post::fromArray($row);
|
||||
return $this->view->render($res, 'pages/post_detail.twig', ['post' => $post]);
|
||||
}
|
||||
|
||||
@@ -101,18 +92,16 @@ class PostController
|
||||
$title = trim((string)($data['title'] ?? ''));
|
||||
$content = trim((string)($data['content'] ?? ''));
|
||||
|
||||
// Créer un objet Post pour valider
|
||||
try {
|
||||
$post = new Post(0, $title, $content);
|
||||
} catch (\InvalidArgumentException) {
|
||||
// Validation échouée, retour à l'admin
|
||||
return $res->withHeader('Location', '/admin')->withStatus(302);
|
||||
}
|
||||
$post = new Post(0, $title, $content);
|
||||
$slug = $post->getSlug();
|
||||
|
||||
// Gérer les collisions
|
||||
$slug = $this->ensureUniqueSlug($slug);
|
||||
|
||||
// Persister en DB
|
||||
$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'),
|
||||
]);
|
||||
@@ -120,6 +109,19 @@ class PostController
|
||||
return $res->withHeader('Location', '/admin')->withStatus(302);
|
||||
}
|
||||
|
||||
private function ensureUniqueSlug(string $slug): string
|
||||
{
|
||||
$original = $slug;
|
||||
$counter = 1;
|
||||
|
||||
while ($this->db->get('post', 'id', ['slug' => $slug])) {
|
||||
$slug = $original . '-' . $counter;
|
||||
$counter++;
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour un article existant.
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user