Feature/ext-blog #14

Merged
deepDiverPaul merged 6 commits from feature/ext-blog into main 2026-12-02 10:22:47 +00:00
4 changed files with 258 additions and 7 deletions
Showing only changes of commit 32582e9279 - Show all commits
@@ -8,6 +8,8 @@ use Plugi\Repositories\BaseRepository;
class PostsRepository extends BaseRepository
{
public const POSTS_PER_PAGE = 10;
protected $table = 'ext__blog_posts';
public function create(array $data)
@@ -39,6 +41,51 @@ class PostsRepository extends BaseRepository
);
}
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';
@@ -3,7 +3,20 @@
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
$posts = (new PostsRepository())->getAllForAdmin();
$postsRepository = new PostsRepository();
$search = is_string($_GET['q'] ?? null) ? trim($_GET['q']) : '';
$pageValue = $_GET['posts_page'] ?? null;
$page = is_string($pageValue) ? filter_var($pageValue, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) : false;
$page = $page === false ? 1 : $page;
$pageResult = $postsRepository->getPageForAdmin($search, $page);
$totalPages = max(1, (int) ceil($pageResult['total'] / PostsRepository::POSTS_PER_PAGE));
if ($page > $totalPages) {
$page = $totalPages;
}
$posts = $pageResult['posts'];
$searchParameters = $search === '' ? [] : ['q' => $search];
$adminPostsUrl = phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'posts']);
$websiteManagerUrl = phpb_url('website_manager');
$categories = (new CategoriesRepository())->getAllForAdmin();
$categoryNames = [];
foreach ($categories as $category) {
@@ -15,7 +28,7 @@ foreach ($categories as $category) {
<div class="space-y-1">
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-primary">Blog extension</p>
<h2 class="text-xl font-bold tracking-tight text-base-content">Posts</h2>
<p class="text-sm text-base-content/60"><?= count($posts) ?> post<?= count($posts) !== 1 ? 's' : '' ?></p>
<p class="text-sm text-base-content/60"><?= phpb_e((string) $pageResult['total']) ?> post<?= $pageResult['total'] !== 1 ? 's' : '' ?></p>
</div>
<a href="<?= phpb_url('website_manager', ['tab' => 'ext--blog', 'action' => 'editPost']) ?>" class="btn btn-primary">
<i class="ph-duotone ph-plus" aria-hidden="true"></i>
@@ -23,7 +36,22 @@ foreach ($categories as $category) {
</a>
</header>
<?php if (empty($posts)): ?>
<form class="flex flex-col gap-3 sm:flex-row sm:items-end" method="get" action="<?= phpb_e($websiteManagerUrl) ?>">
<input type="hidden" name="tab" value="ext--blog">
<input type="hidden" name="action" value="posts">
<label class="flex w-full max-w-md flex-col gap-2">
<span class="text-sm font-medium">Search posts</span>
<input class="input w-full" type="search" name="q" value="<?= phpb_e($search) ?>">
</label>
<button class="btn" type="submit">Search</button>
</form>
<?php if ($pageResult['total'] === 0 && $search !== ''): ?>
<div class="alert alert-info" role="status">
No posts found for &quot;<?= phpb_e($search) ?>&quot;.
<a class="link link-hover" href="<?= phpb_e($adminPostsUrl) ?>">Clear search</a>
</div>
<?php elseif ($pageResult['total'] === 0): ?>
<div class="card border border-dashed border-base-300 bg-base-100 shadow-sm" role="status">
<div class="card-body items-center gap-3 px-5 py-12 text-center sm:py-16">
<span class="grid size-14 place-items-center rounded-2xl bg-primary/10 text-primary">
@@ -56,7 +84,7 @@ foreach ($categories as $category) {
<div class="font-medium"><?= phpb_e($post['title']) ?></div>
<div class="text-xs text-base-content/60">/<?= phpb_e($post['slug']) ?></div>
</td>
<td><?= phpb_e($categoryNames[$post['category_id']] ?? '—') ?></td>
<td><?= phpb_e($post['category_id'] === null ? '—' : ($categoryNames[$post['category_id']] ?? '—')) ?></td>
<td><span class="badge <?= $post['status'] === 'published' ? 'badge-success' : 'badge-warning' ?>"><?= phpb_e(ucfirst($post['status'])) ?></span></td>
<td><?= phpb_e($post['published_at'] ?? '—') ?></td>
<td>
@@ -79,4 +107,22 @@ foreach ($categories as $category) {
</table>
</div>
<?php endif; ?>
<?php if ($totalPages > 1): ?>
<nav class="flex justify-center" aria-label="Admin post pages">
<div class="join">
<?php if ($page > 1): ?>
<a class="join-item btn btn-sm" rel="prev" href="<?= phpb_e($adminPostsUrl . '&' . http_build_query($searchParameters + ['posts_page' => $page - 1])) ?>">Previous</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Previous</span>
<?php endif; ?>
<span class="join-item btn btn-sm btn-disabled" aria-current="page">Page <?= phpb_e($page) ?> of <?= phpb_e($totalPages) ?></span>
<?php if ($page < $totalPages): ?>
<a class="join-item btn btn-sm" rel="next" href="<?= phpb_e($adminPostsUrl . '&' . http_build_query($searchParameters + ['posts_page' => $page + 1])) ?>">Next</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Next</span>
<?php endif; ?>
</div>
</nav>
<?php endif; ?>
</section>
@@ -1,10 +1,32 @@
<?php
$posts = (new \Plugi\Extensions\Blog\PostsRepository())->getPublishedForListing();
$postsRepository = new \Plugi\Extensions\Blog\PostsRepository();
$search = is_string($_GET['q'] ?? null) ? trim($_GET['q']) : '';
$pageValue = $_GET['page'] ?? null;
$page = is_string($pageValue) ? filter_var($pageValue, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]) : false;
$page = $page === false ? 1 : $page;
$listingPath = isset($_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI']) ? phpb_full_url(phpb_current_relative_url(true)) : '/';
$pageResult = $postsRepository->getPageForListing($search, $page);
$totalPages = max(1, (int) ceil($pageResult['total'] / \Plugi\Extensions\Blog\PostsRepository::POSTS_PER_PAGE));
if ($page > $totalPages) {
$page = $totalPages;
}
$posts = $pageResult['posts'];
$searchParameters = $search === '' ? [] : ['q' => $search];
?>
<section class="space-y-6" aria-label="Blog posts">
<?php if (empty($posts)): ?>
<div class="alert alert-info" role="status">No published posts yet.</div>
<form class="flex flex-col gap-3 sm:flex-row sm:items-end" method="get" action="<?= phpb_e($listingPath) ?>">
<label class="flex w-full max-w-md flex-col gap-2">
<span class="text-sm font-medium">Search posts</span>
<input class="input w-full" type="search" name="q" value="<?= phpb_e($search) ?>" />
</label>
<button class="btn" type="submit">Search</button>
</form>
<?php if ($pageResult['total'] === 0): ?>
<div class="alert alert-info" role="status">
<?= $search === '' ? 'No published posts yet.' : 'No published posts match &quot;' . phpb_e($search) . '&quot;.' ?>
</div>
<?php else: ?>
<div class="grid gap-6 md:grid-cols-2">
<?php foreach ($posts as $post): ?>
@@ -38,4 +60,22 @@ $posts = (new \Plugi\Extensions\Blog\PostsRepository())->getPublishedForListing(
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($totalPages > 1): ?>
<nav class="flex justify-center" aria-label="Blog post pages">
<div class="join">
<?php if ($page > 1): ?>
<a class="join-item btn btn-sm" rel="prev" href="<?= phpb_e($listingPath . '?' . http_build_query($searchParameters + ['page' => $page - 1])) ?>">Previous</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Previous</span>
<?php endif; ?>
<span class="join-item btn btn-sm btn-disabled" aria-current="page">Page <?= phpb_e($page) ?> of <?= phpb_e($totalPages) ?></span>
<?php if ($page < $totalPages): ?>
<a class="join-item btn btn-sm" rel="next" href="<?= phpb_e($listingPath . '?' . http_build_query($searchParameters + ['page' => $page + 1])) ?>">Next</a>
<?php else: ?>
<span class="join-item btn btn-sm btn-disabled" aria-disabled="true">Next</span>
<?php endif; ?>
</div>
</nav>
<?php endif; ?>
</section>
@@ -110,6 +110,13 @@ function renderBlogDetail(?string $slug): string
return renderBlogBlock('post-detail');
}
function renderBlogAdminList(): string
{
ob_start();
include dirname(__DIR__) . '/admin/Views/ListPosts.php';
return (string) ob_get_clean();
}
$_ENV['DATABASE_PREFIX'] = 'test_';
$phpb_db = new BlogTestDatabase();
$phpb_db->createSchema();
@@ -185,6 +192,7 @@ assertBlog(str_contains(renderBlogDetail('second-post'), 'Article not found'), '
assertBlog($datedPost['published_at'] === str_replace('T', ' ', $pastPublication) . ':00', 'A valid local publication date should be normalized for storage.');
assertBlog($datedPost['body'] === " Draft body\n", 'Post body whitespace should be preserved.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Invalid date', 'slug' => 'invalid-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => 'not-a-date',
]), 'Invalid publication dates should be rejected.');
@@ -233,7 +241,117 @@ assertBlog($posts->findWithId($secondPost['id'])['category_id'] === null, 'Delet
assertBlog($posts->destroy($secondPost['id']) === true, 'A post should be deleted.');
assertBlog($posts->destroy($datedPost['id']) === true, 'A dated post should be deleted.');
assertBlog($posts->destroy($olderPost['id']) === true, 'An older published post should be deleted.');
assertBlog($posts->destroy($post['id']) === true, 'The remaining draft should be deleted.');
assertBlog($categories->findWithId($category['id']) === null && $posts->findWithId($secondPost['id']) === null, 'Deleted records should no longer be found.');
assertBlog(str_contains(renderBlogListing(), 'No published posts yet.'), 'The listing should show an empty state when no posts are published.');
$phpb_config = ['website_manager' => ['url' => '/website-manager']];
$_GET = [];
assertBlog(str_contains(renderBlogAdminList(), 'No posts yet'), 'The admin list should show its empty-list state when no posts exist.');
for ($index = 1; $index <= 12; $index++) {
$number = str_pad((string) $index, 2, '0', STR_PAD_LEFT);
$batchPost = $posts->create([
'title' => 'Pagination batch ' . $number,
'slug' => 'pagination-batch-' . $number,
'excerpt' => 'Batch excerpt',
'body' => 'Batch body',
'category_id' => '',
'status' => $index === 12 ? 'draft' : 'published',
'published_at' => '2025-01-' . $number . 'T00:00',
]);
$phpb_db->query('UPDATE test_ext__blog_posts SET updated_at = ? WHERE id = ?', ['2025-02-' . $number . ' 00:00:00', $batchPost['id']]);
}
foreach ([
'title' => 'TitleSearchMarker',
'slug' => 'slugsearchmarker',
'excerpt' => 'ExcerptSearchMarker',
'body' => 'BodySearchMarker',
] as $field => $term) {
$fieldPost = [
'title' => 'Field-only test post',
'slug' => 'field-only-test-post',
'excerpt' => 'Field-only excerpt',
'body' => 'Field-only body',
'category_id' => '',
'status' => 'published',
'published_at' => '2025-03-01T00:00',
];
$fieldPost[$field] = $term;
$fieldPost['slug'] = $field === 'slug' ? $term : 'field-only-' . $field;
$fieldPost = $posts->create($fieldPost);
$adminMatch = $posts->getPageForAdmin($term, 1);
$publicMatch = $posts->getPageForListing($term, 1);
assertBlog($adminMatch['total'] === 1 && $adminMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Admin search should match the ' . $field . ' field.');
assertBlog($publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $fieldPost['slug'], 'Public search should match the ' . $field . ' field.');
}
foreach ([
['term' => '100%', 'match' => 'literal-percent', 'title' => 'Price 100% complete', 'decoy' => 'wildcard-percent-decoy', 'decoyTitle' => 'Price 100X complete'],
['term' => 'under_score', 'match' => 'literal-underscore', 'title' => 'under_score example', 'decoy' => 'wildcard-underscore-decoy', 'decoyTitle' => 'underXscore example'],
['term' => 'bang!mark', 'match' => 'literal-escape-character', 'title' => 'bang!mark example', 'decoy' => 'escape-character-decoy', 'decoyTitle' => 'bangXmark example'],
] as $literalSearch) {
foreach ([[$literalSearch['match'], $literalSearch['title']], [$literalSearch['decoy'], $literalSearch['decoyTitle']]] as [$slug, $title]) {
$posts->create([
'title' => $title,
'slug' => $slug,
'excerpt' => '',
'body' => 'Search wildcard regression test',
'category_id' => '',
'status' => 'published',
'published_at' => '2025-03-01T00:00',
]);
}
$adminMatch = $posts->getPageForAdmin($literalSearch['term'], 1);
$publicMatch = $posts->getPageForListing($literalSearch['term'], 1);
assertBlog($adminMatch['total'] === 1 && $adminMatch['posts'][0]['slug'] === $literalSearch['match'], 'Admin search should treat LIKE metacharacters literally.');
assertBlog($publicMatch['total'] === 1 && $publicMatch['posts'][0]['slug'] === $literalSearch['match'], 'Public search should treat LIKE metacharacters literally.');
}
$adminFirstPage = $posts->getPageForAdmin('pagination', 1);
$adminLastPage = $posts->getPageForAdmin('pagination', 2);
assertBlog($adminFirstPage['total'] === 12 && count($adminFirstPage['posts']) === 10, 'Admin pagination should report all matching posts and cap each page at ten.');
assertBlog($adminFirstPage['posts'][0]['slug'] === 'pagination-batch-12' && $adminFirstPage['posts'][9]['slug'] === 'pagination-batch-03', 'Admin pages should preserve the newest-updated-first order.');
assertBlog(count($adminLastPage['posts']) === 2 && $adminLastPage['posts'][0]['slug'] === 'pagination-batch-02', 'The admin final page should contain the remaining posts in order.');
assertBlog($posts->getPageForAdmin('pagination', 0)['posts'][0]['slug'] === 'pagination-batch-12', 'Invalid low page numbers should normalize to the first page.');
assertBlog($posts->getPageForAdmin('pagination', PHP_INT_MAX)['posts'][0]['slug'] === 'pagination-batch-02', 'Oversized page numbers should safely resolve to the last matching page.');
$publicFirstPage = $posts->getPageForListing('pagination', 1);
$publicLastPage = $posts->getPageForListing('pagination', 2);
assertBlog($publicFirstPage['total'] === 11 && count($publicFirstPage['posts']) === 10, 'Public pagination should exclude the matching draft and report published totals.');
assertBlog($publicFirstPage['posts'][0]['slug'] === 'pagination-batch-11', 'Public pages should preserve newest-published-first order.');
assertBlog(count($publicLastPage['posts']) === 1 && $publicLastPage['posts'][0]['slug'] === 'pagination-batch-01', 'The public final page should contain its remaining published post.');
$noMatches = $posts->getPageForAdmin("pagination' OR '1'='1", 1);
assertBlog($noMatches['total'] === 0 && $noMatches['posts'] === [], 'Search input should be treated as a value rather than SQL.');
$_SERVER['HTTPS'] = 'on';
$_SERVER['SERVER_NAME'] = 'blog.example';
$_SERVER['SERVER_PORT'] = 443;
$_ENV['BASE_URL'] = 'https://blog.example/app';
$_SERVER['REQUEST_URI'] = '/app/news?keep=old';
$_GET = ['q' => 'pagination', 'page' => '2'];
$publicSearchPage = renderBlogListing();
assertBlog(str_contains($publicSearchPage, 'Pagination batch 01') && !str_contains($publicSearchPage, 'Pagination batch 11'), 'The public block should render only the requested search page.');
assertBlog(str_contains($publicSearchPage, 'action="https://blog.example/app/news"') && str_contains($publicSearchPage, 'name="q" value="pagination"'), 'The public search form should submit to the current path and retain its search value.');
assertBlog(str_contains($publicSearchPage, 'href="https://blog.example/app/news?q=pagination&amp;page=1"') && str_contains($publicSearchPage, 'Page 2 of 2'), 'Public pagination should retain the search term and current page position.');
$_GET = ['q' => 'pagination', 'page' => '0'];
assertBlog(str_contains(renderBlogListing(), 'Pagination batch 11'), 'Invalid public page values should safely show the first page.');
$_GET = ['q' => 'no-such-post'];
$publicNoMatches = renderBlogListing();
assertBlog(str_contains($publicNoMatches, 'No published posts match &quot;no-such-post&quot;') && !str_contains($publicNoMatches, 'No published posts yet.'), 'The public block should distinguish no matches from an empty blog.');
$_GET = ['q' => 'pagination', 'page' => '99', 'posts_page' => '2'];
$adminSearchPage = renderBlogAdminList();
assertBlog(str_contains($adminSearchPage, 'Pagination batch 02') && str_contains($adminSearchPage, 'Pagination batch 01') && !str_contains($adminSearchPage, 'Pagination batch 12'), 'The admin list should render only the requested page.');
assertBlog(str_contains($adminSearchPage, 'name="tab" value="ext--blog"') && str_contains($adminSearchPage, 'name="q" value="pagination"'), 'The admin search form should retain the extension route and search term.');
assertBlog(str_contains($adminSearchPage, 'href="https://blog.example/app/website-manager?tab=ext--blog&amp;action=posts&amp;q=pagination&amp;posts_page=1"') && str_contains($adminSearchPage, 'Page 2 of 2'), 'Admin pagination should preserve the extension route, search term, and posts_page parameter.');
$_GET = ['q' => 'pagination', 'page' => '2', 'posts_page' => '1'];
$adminFirstPageHtml = renderBlogAdminList();
assertBlog(str_contains($adminFirstPageHtml, 'Pagination batch 12') && str_contains($adminFirstPageHtml, '>Draft</span>'), 'The admin list should include matching drafts.');
$_GET = ['q' => 'pagination', 'page' => '2', 'posts_page' => '0'];
assertBlog(str_contains(renderBlogAdminList(), 'Pagination batch 12'), 'Invalid admin page values should safely show the first page.');
$_GET = ['q' => 'no-such-post'];
$adminNoMatches = renderBlogAdminList();
assertBlog(str_contains($adminNoMatches, 'No posts found for &quot;no-such-post&quot;') && !str_contains($adminNoMatches, 'No posts yet'), 'The admin list should distinguish no matches from an empty post list.');
fwrite(STDOUT, "Blog repository tests passed.\n");