The PostsRepository now includes methods for fetching paginated and searched posts. The admin and public views include search forms, pagination controls, and display total counts instead of just post counts. Tests verify the new functionality including special character search handling and pagination limits.
175 lines
7.2 KiB
PHP
175 lines
7.2 KiB
PHP
<?php
|
||
|
||
namespace Plugi\Extensions\Blog;
|
||
|
||
use DateTimeImmutable;
|
||
use InvalidArgumentException;
|
||
use Plugi\Repositories\BaseRepository;
|
||
|
||
class PostsRepository extends BaseRepository
|
||
{
|
||
public const POSTS_PER_PAGE = 10;
|
||
|
||
protected $table = 'ext__blog_posts';
|
||
|
||
public function create(array $data)
|
||
{
|
||
return parent::create($this->validatedData($data));
|
||
}
|
||
|
||
public function update($instance, array $data)
|
||
{
|
||
$id = is_array($instance) ? ($instance['id'] ?? null) : ($instance->id ?? null);
|
||
if (!is_numeric($id) || (int) $id < 1 || $this->findWithId($id) === null) {
|
||
return false;
|
||
}
|
||
|
||
return parent::update(['id' => (int) $id], $this->validatedData($data, (int) $id));
|
||
}
|
||
|
||
public function getAllForAdmin(): array
|
||
{
|
||
return $this->db->select("SELECT * FROM {$this->table} ORDER BY updated_at DESC, id DESC", []);
|
||
}
|
||
|
||
public function getPublishedForListing(): array
|
||
{
|
||
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
|
||
return $this->db->select(
|
||
"SELECT posts.*, categories.name AS category_name FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id WHERE posts.status = ? ORDER BY posts.published_at DESC, posts.id DESC",
|
||
['published']
|
||
);
|
||
}
|
||
|
||
public function getPageForAdmin(string $search, int $page): array
|
||
{
|
||
return $this->getPostPage($search, $page, false);
|
||
}
|
||
|
||
public function getPageForListing(string $search, int $page): array
|
||
{
|
||
return $this->getPostPage($search, $page, true);
|
||
}
|
||
|
||
private function getPostPage(string $search, int $page, bool $publishedOnly): array
|
||
{
|
||
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
|
||
$from = $publishedOnly
|
||
? "FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id"
|
||
: "FROM {$this->table} posts";
|
||
$filters = [];
|
||
$parameters = [];
|
||
|
||
if ($publishedOnly) {
|
||
$filters[] = 'posts.status = ?';
|
||
$parameters[] = 'published';
|
||
}
|
||
if (trim($search) !== '') {
|
||
$filters[] = '(posts.title LIKE ? ESCAPE \'!\' OR posts.slug LIKE ? ESCAPE \'!\' OR posts.excerpt LIKE ? ESCAPE \'!\' OR posts.body LIKE ? ESCAPE \'!\')';
|
||
$pattern = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], trim($search)) . '%';
|
||
array_push($parameters, $pattern, $pattern, $pattern, $pattern);
|
||
}
|
||
|
||
$where = $filters === [] ? '' : ' WHERE ' . implode(' AND ', $filters);
|
||
$total = $this->db->select("SELECT COUNT(*) AS total {$from}{$where}", $parameters)[0]['total'] ?? 0;
|
||
$page = min(max(1, $page), max(1, (int) ceil((int) $total / self::POSTS_PER_PAGE)));
|
||
$offset = ($page - 1) * self::POSTS_PER_PAGE;
|
||
$select = $publishedOnly
|
||
? 'SELECT posts.*, categories.name AS category_name'
|
||
: 'SELECT posts.*';
|
||
$order = $publishedOnly ? 'posts.published_at DESC, posts.id DESC' : 'posts.updated_at DESC, posts.id DESC';
|
||
$posts = $this->db->select(
|
||
"{$select} {$from}{$where} ORDER BY {$order} LIMIT " . self::POSTS_PER_PAGE . " OFFSET {$offset}",
|
||
$parameters
|
||
);
|
||
|
||
return ['posts' => $posts, 'total' => (int) $total];
|
||
}
|
||
|
||
public function findPublishedBySlug(string $slug): ?array
|
||
{
|
||
$categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories';
|
||
$posts = $this->db->select(
|
||
"SELECT posts.*, categories.name AS category_name FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id WHERE posts.slug = ? AND posts.status = ? LIMIT 1",
|
||
[$slug, 'published']
|
||
);
|
||
|
||
return $posts[0] ?? null;
|
||
}
|
||
|
||
public function clearCategory(int $categoryId): bool
|
||
{
|
||
return $this->db->query("UPDATE {$this->table} SET category_id = NULL WHERE category_id = ?", [$categoryId]);
|
||
}
|
||
|
||
private function validatedData(array $data, ?int $postId = null): array
|
||
{
|
||
$title = is_string($data['title'] ?? null) ? trim($data['title']) : '';
|
||
$slug = is_string($data['slug'] ?? null) ? trim($data['slug']) : '';
|
||
$excerpt = is_string($data['excerpt'] ?? null) ? trim($data['excerpt']) : '';
|
||
$body = is_string($data['body'] ?? null) ? $data['body'] : '';
|
||
$status = is_string($data['status'] ?? null) ? $data['status'] : '';
|
||
|
||
if ($title === '' || mb_strlen($title) > 255) {
|
||
throw new InvalidArgumentException('A title of 1–255 characters is required.');
|
||
}
|
||
if (strlen($slug) > 191 || !preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) {
|
||
throw new InvalidArgumentException('Use a lowercase slug with letters, numbers, and single hyphens.');
|
||
}
|
||
foreach ($this->findWhere('slug', $slug) as $post) {
|
||
if ((int) $post['id'] !== $postId) {
|
||
throw new InvalidArgumentException('That post slug is already in use.');
|
||
}
|
||
}
|
||
if (!in_array($status, ['draft', 'published'], true)) {
|
||
throw new InvalidArgumentException('Choose draft or published status.');
|
||
}
|
||
if ($status === 'published' && trim($body) === '') {
|
||
throw new InvalidArgumentException('Add the post body before publishing.');
|
||
}
|
||
|
||
$categoryId = $data['category_id'] ?? '';
|
||
if ($categoryId === '' || $categoryId === null) {
|
||
$categoryId = null;
|
||
} elseif (!is_scalar($categoryId) || !ctype_digit((string) $categoryId) || (int) $categoryId < 1 || (new CategoriesRepository())->findWithId((int) $categoryId) === null) {
|
||
throw new InvalidArgumentException('Choose an existing category.');
|
||
} else {
|
||
$categoryId = (int) $categoryId;
|
||
}
|
||
|
||
$publishedAt = $this->validatedPublicationDate($data['published_at'] ?? '', $status);
|
||
|
||
return [
|
||
'title' => $title,
|
||
'slug' => $slug,
|
||
'excerpt' => $excerpt,
|
||
'body' => $body,
|
||
'category_id' => $categoryId,
|
||
'status' => $status,
|
||
'published_at' => $publishedAt,
|
||
];
|
||
}
|
||
|
||
private function validatedPublicationDate(mixed $value, string $status): ?string
|
||
{
|
||
if ($value === null || $value === '') {
|
||
return $status === 'published' ? date('Y-m-d H:i:s') : null;
|
||
}
|
||
if (!is_string($value)) {
|
||
throw new InvalidArgumentException('Enter a valid publication date.');
|
||
}
|
||
|
||
$value = trim($value);
|
||
$format = str_contains($value, 'T') ? 'Y-m-d\\TH:i' : 'Y-m-d H:i:s';
|
||
$date = DateTimeImmutable::createFromFormat('!' . $format, $value);
|
||
$errors = DateTimeImmutable::getLastErrors();
|
||
if ($date === false || ($errors !== false && ($errors['warning_count'] > 0 || $errors['error_count'] > 0)) || $date->format($format) !== $value) {
|
||
throw new InvalidArgumentException('Enter a valid publication date.');
|
||
}
|
||
if ($date > new DateTimeImmutable()) {
|
||
throw new InvalidArgumentException('Publication dates cannot be in the future.');
|
||
}
|
||
|
||
return $date->format('Y-m-d H:i:s');
|
||
}
|
||
} |