Added slug db column

This commit is contained in:
julien
2026-03-09 15:31:16 +01:00
parent 4d678f1211
commit 5b37d2bcd8
2 changed files with 23 additions and 20 deletions

View File

@@ -65,6 +65,7 @@ $db->pdo->exec("
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL, title TEXT NOT NULL,
content TEXT NOT NULL, content TEXT NOT NULL,
slug TEXT UNIQUE NOT NULL DEFAULT '',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
) )

View File

@@ -37,23 +37,14 @@ class PostController
{ {
$slug = (string)($args['slug'] ?? ''); $slug = (string)($args['slug'] ?? '');
// Récupérer tous les posts et chercher celui qui correspond au slug $row = $this->db->get('post', '*', ['slug' => $slug]);
$rows = $this->db->select('post', '*', ['ORDER' => ['id' => 'DESC']]);
$post = null;
foreach ($rows ?: [] as $row) { if (!$row) {
$postObj = Post::fromArray($row);
if ($postObj->getSlug() === $slug) {
$post = $postObj;
break;
}
}
if (!$post) {
$res->getBody()->write('Article non trouvé'); $res->getBody()->write('Article non trouvé');
return $res->withStatus(404); return $res->withStatus(404);
} }
$post = Post::fromArray($row);
return $this->view->render($res, 'pages/post_detail.twig', ['post' => $post]); return $this->view->render($res, 'pages/post_detail.twig', ['post' => $post]);
} }
@@ -101,18 +92,16 @@ class PostController
$title = trim((string)($data['title'] ?? '')); $title = trim((string)($data['title'] ?? ''));
$content = trim((string)($data['content'] ?? '')); $content = trim((string)($data['content'] ?? ''));
// Créer un objet Post pour valider
try {
$post = new Post(0, $title, $content); $post = new Post(0, $title, $content);
} catch (\InvalidArgumentException) { $slug = $post->getSlug();
// Validation échouée, retour à l'admin
return $res->withHeader('Location', '/admin')->withStatus(302); // Gérer les collisions
} $slug = $this->ensureUniqueSlug($slug);
// Persister en DB
$this->db->insert('post', [ $this->db->insert('post', [
'title' => $post->getTitle(), 'title' => $post->getTitle(),
'content' => $post->getContent(), 'content' => $post->getContent(),
'slug' => $slug,
'created_at' => date('Y-m-d H:i:s'), 'created_at' => date('Y-m-d H:i:s'),
'updated_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); 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. * Met à jour un article existant.
*/ */