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'; $uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads'; $posts = $this->db->select( "SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%' WHERE posts.status = ? ORDER BY posts.published_at DESC, posts.id DESC", ['published'] ); return array_map(fn(array $post): array => $this->resolveFeaturedImage($post), $posts); } 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'; $uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads'; $from = $publishedOnly ? "FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%'" : "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, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text' : '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 ); if ($publishedOnly) { $posts = array_map(fn(array $post): array => $this->resolveFeaturedImage($post), $posts); } return ['posts' => $posts, 'total' => (int) $total]; } public function findPublishedBySlug(string $slug): ?array { $categoriesTable = $_ENV['DATABASE_PREFIX'] . 'ext__blog_categories'; $uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads'; $posts = $this->db->select( "SELECT posts.*, categories.name AS category_name, featured_image.public_id AS featured_image_public_id, featured_image.original_file AS featured_image_original_file, featured_image.alt_text AS featured_image_alt_text FROM {$this->table} posts LEFT JOIN {$categoriesTable} categories ON categories.id = posts.category_id LEFT JOIN {$uploadsTable} featured_image ON featured_image.public_id = posts.featured_image_id AND LOWER(featured_image.mime_type) LIKE 'image/%' WHERE posts.slug = ? AND posts.status = ? LIMIT 1", [$slug, 'published'] ); return isset($posts[0]) ? $this->resolveFeaturedImage($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; } $featuredImageId = $data['featured_image_id'] ?? ''; if ($featuredImageId === '' || $featuredImageId === null) { $featuredImageId = null; } elseif (!is_string($featuredImageId) || strlen($featuredImageId) > 50) { throw new InvalidArgumentException('Choose an existing image upload.'); } else { $uploadsTable = $_ENV['DATABASE_PREFIX'] . 'uploads'; $images = $this->db->select( "SELECT public_id FROM {$uploadsTable} WHERE public_id = ? AND LOWER(mime_type) LIKE 'image/%' LIMIT 1", [$featuredImageId] ); if ($images === []) { throw new InvalidArgumentException('Choose an existing image upload.'); } $featuredImageId = $images[0]['public_id']; } $publishedAt = $this->validatedPublicationDate($data['published_at'] ?? '', $status); return [ 'title' => $title, 'slug' => $slug, 'excerpt' => $excerpt, 'body' => $body, 'featured_image_id' => $featuredImageId, 'category_id' => $categoryId, 'status' => $status, 'published_at' => $publishedAt, ]; } private function resolveFeaturedImage(array $post): array { $publicId = $post['featured_image_public_id'] ?? null; $originalFile = $post['featured_image_original_file'] ?? null; if (is_string($publicId) && $publicId !== '' && is_string($originalFile) && $originalFile !== '') { $image = new \Plugi\UploadedFile(); $image->public_id = $publicId; $image->original_file = $originalFile; $post['featured_image_url'] = $image->getUrl(); } else { $post['featured_image_url'] = null; $post['featured_image_alt_text'] = null; } unset($post['featured_image_public_id'], $post['featured_image_original_file']); return $post; } 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'); } }