128 lines
5.1 KiB
PHP
128 lines
5.1 KiB
PHP
<?php
|
||
|
||
namespace Plugi\Extensions\Blog;
|
||
|
||
use DateTimeImmutable;
|
||
use InvalidArgumentException;
|
||
use Plugi\Repositories\BaseRepository;
|
||
|
||
class PostsRepository extends BaseRepository
|
||
{
|
||
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 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');
|
||
}
|
||
} |