Files
plugi/extensions/plugi-ext-blog/tests/BlogRepositoriesTest.php
T
2026-12-02 11:09:09 +01:00

239 lines
12 KiB
PHP

<?php
use Plugi\Core\DB;
use Plugi\Extensions\Blog\CategoriesRepository;
use Plugi\Extensions\Blog\PostsRepository;
require_once dirname(__DIR__, 3) . '/plugi-core/src/Extensions.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Core/DB.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Core/helpers.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Repositories/BaseRepository.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Contracts/PageContract.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Contracts/ThemeContract.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Page.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/PageRenderer.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BaseModel.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BaseController.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/ThemeBlock.php';
require_once dirname(__DIR__, 3) . '/plugi-core/src/Modules/GrapesJS/Block/BlockRenderer.php';
require_once dirname(__DIR__) . '/admin/Classes/PostsRepository.php';
require_once dirname(__DIR__) . '/admin/Classes/CategoriesRepository.php';
$blogConfig = require dirname(__DIR__) . '/config.php';
\Plugi\Extensions::registerConfig('blog', $blogConfig);
require_once dirname(__DIR__) . '/extension.php';
class BlogTestDatabase extends DB
{
public function __construct()
{
$this->pdo = new PDO('sqlite::memory:');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->databaseName = 'blog_test';
}
public function createSchema(): void
{
$this->query('CREATE TABLE test_ext__blog_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title VARCHAR(255) NOT NULL,
slug VARCHAR(191) NOT NULL UNIQUE,
excerpt TEXT NOT NULL,
body TEXT NOT NULL,
category_id INTEGER NULL,
status VARCHAR(20) NOT NULL,
published_at DATETIME NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)');
$this->query('CREATE TABLE test_ext__blog_categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) NOT NULL,
slug VARCHAR(191) NOT NULL UNIQUE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)');
}
}
class BlogTestTheme implements \Plugi\Contracts\ThemeContract
{
public function getThemeBlocks()
{
return [];
}
public function getThemeLayouts()
{
return [];
}
public function getFolder()
{
return '';
}
}
function assertBlog(bool $condition, string $message): void
{
if (!$condition) {
throw new RuntimeException($message);
}
}
function expectBlogValidation(callable $callback, string $message): void
{
try {
$callback();
} catch (InvalidArgumentException) {
return;
}
throw new RuntimeException($message);
}
function renderBlogBlock(string $slug): string
{
$theme = new BlogTestTheme();
$page = new \Plugi\Page();
$themeBlock = new \Plugi\ThemeBlock($theme, \Plugi\Extensions::getBlock($slug), true, $slug);
return (new \Plugi\Modules\GrapesJS\Block\BlockRenderer($theme, $page))->render($themeBlock);
}
function renderBlogListing(): string
{
return renderBlogBlock('post-list');
}
function renderBlogDetail(?string $slug): string
{
$GLOBALS['phpb_route_parameters'] = $slug === null ? [] : ['slug' => $slug];
return renderBlogBlock('post-detail');
}
$_ENV['DATABASE_PREFIX'] = 'test_';
$phpb_db = new BlogTestDatabase();
$phpb_db->createSchema();
assertBlog(isset($phpb_db->getDBDefinition()['ext__blog_posts'], $phpb_db->getDBDefinition()['ext__blog_categories']), 'The blog tables should be included in the core database definition.');
assertBlog(isset(\Plugi\Extensions::getBackends()['ext--blog']), 'The blog admin backend should be registered.');
assertBlog(count(array_intersect(['/ext--blog/save-post', '/ext--blog/delete-post', '/ext--blog/save-category', '/ext--blog/delete-category'], array_keys(\Plugi\Extensions::getRoutes()))) === 4, 'Blog CRUD routes should be registered.');
assertBlog(\Plugi\Extensions::getBlock('post-list') === dirname(__DIR__) . '/blocks/post-list', 'The published-post block should be registered.');
assertBlog((require dirname(__DIR__) . '/blocks/post-list/config.php')['cache'] === false, 'The listing block should avoid stale cached post data.');
assertBlog(\Plugi\Extensions::getBlock('post-detail') === dirname(__DIR__) . '/blocks/post-detail', 'The post-detail block should be registered.');
assertBlog((require dirname(__DIR__) . '/blocks/post-detail/config.php')['cache'] === false, 'The detail block should avoid stale route-specific output.');
$posts = new PostsRepository();
$categories = new CategoriesRepository();
$category = $categories->create(['name' => 'News', 'slug' => 'news']);
assertBlog(is_array($category) && (int) $category['id'] > 0, 'Category creation should return the new category.');
$post = $posts->create([
'title' => 'First post',
'slug' => 'first-post',
'excerpt' => 'A short summary',
'body' => 'Post body',
'category_id' => $category['id'],
'status' => 'published',
'published_at' => '',
]);
assertBlog(is_array($post) && $post['status'] === 'published', 'A valid published post should be created.');
assertBlog($post['published_at'] !== null, 'Publishing without a date should set the current publication timestamp.');
$olderPost = $posts->create([
'title' => 'Older published post',
'slug' => 'older-published-post',
'excerpt' => 'Older excerpt',
'body' => '<script>alert("x")</script>&safe',
'category_id' => '',
'status' => 'published',
'published_at' => '2020-01-01T00:00',
]);
$pastPublication = date('Y-m-d\\TH:i', time() - 3600);
$datedPost = $posts->create([
'title' => 'Dated draft',
'slug' => 'dated-draft',
'excerpt' => '',
'body' => " Draft body\n",
'category_id' => '',
'status' => 'draft',
'published_at' => $pastPublication,
]);
$secondPost = $posts->create([
'title' => 'Second post',
'slug' => 'second-post',
'excerpt' => '',
'body' => '',
'category_id' => $category['id'],
'status' => 'draft',
'published_at' => '',
]);
$publishedPosts = $posts->getPublishedForListing();
assertBlog(count($publishedPosts) === 2, 'The public listing should exclude drafts.');
assertBlog($publishedPosts[0]['slug'] === $post['slug'] && $publishedPosts[0]['category_name'] === 'News', 'Published posts should be newest first and include their category name.');
assertBlog($publishedPosts[1]['slug'] === $olderPost['slug'], 'Older published posts should follow newer posts.');
$_ENV['BASE_URL'] = 'https://blog.example';
$listingHtml = renderBlogListing();
assertBlog(str_contains($listingHtml, 'href="https://blog.example/blog/first-post"'), 'The listing should link to the configured post detail URL.');
assertBlog(strpos($listingHtml, 'first-post') < strpos($listingHtml, 'older-published-post'), 'The rendered listing should preserve newest-first order.');
assertBlog(!str_contains($listingHtml, 'dated-draft') && !str_contains($listingHtml, 'second-post'), 'Draft posts should not appear in the rendered listing.');
$detailHtml = renderBlogDetail('older-published-post');
assertBlog(str_contains($detailHtml, '<h1 class="text-3xl font-bold tracking-tight text-base-content sm:text-4xl">Older published post</h1>'), 'The detail block should resolve a published post from the named slug route parameter.');
assertBlog(str_contains($detailHtml, '&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;&amp;safe') && !str_contains($detailHtml, '<script>alert'), 'The detail block should safely escape post bodies.');
assertBlog(str_contains(renderBlogDetail(null), 'Article not found'), 'A missing route slug should render a not-found state.');
assertBlog(str_contains(renderBlogDetail('unknown-post'), 'Article not found'), 'An unknown route slug should render a not-found state.');
assertBlog(str_contains(renderBlogDetail('dated-draft'), 'Article not found'), 'An unpublished post should render a not-found state.');
assertBlog(str_contains(renderBlogDetail('second-post'), 'Article not found'), 'A draft post should render a not-found state.');
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.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Future date', 'slug' => 'future-date', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => date('Y-m-d\\TH:i', time() + 86400),
]), 'Future publication dates should be rejected.');
$updated = $posts->update(['id' => $post['id']], [
'title' => 'Updated post',
'slug' => 'updated-post',
'excerpt' => '',
'body' => 'Updated body',
'category_id' => '',
'status' => 'draft',
'published_at' => '',
]);
assertBlog($updated === true, 'An existing post should update.');
$updatedPost = $posts->findWithId($post['id']);
assertBlog($updatedPost['title'] === 'Updated post' && $updatedPost['category_id'] === null && $updatedPost['published_at'] === null, 'Post updates should persist edited fields and clear optional values.');
assertBlog(is_array($secondPost), 'A draft with an empty body should be saved.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Duplicate post', 'slug' => 'second-post', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Duplicate post slugs should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Bad slug', 'slug' => 'Invalid Slug', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'draft', 'published_at' => '',
]), 'Invalid post slugs should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Bad status', 'slug' => 'bad-status', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'scheduled', 'published_at' => '',
]), 'Unsupported post statuses should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'Missing category', 'slug' => 'missing-category', 'excerpt' => '', 'body' => '', 'category_id' => '999', 'status' => 'draft', 'published_at' => '',
]), 'Unknown categories should be rejected.');
expectBlogValidation(fn() => $posts->create([
'title' => 'No body', 'slug' => 'no-body', 'excerpt' => '', 'body' => '', 'category_id' => '', 'status' => 'published', 'published_at' => '',
]), 'Published posts should require body content.');
expectBlogValidation(fn() => $categories->create(['name' => 'Duplicate', 'slug' => 'news']), 'Duplicate category slugs should be rejected.');
expectBlogValidation(fn() => $categories->create(['name' => 'Bad slug', 'slug' => 'not a slug']), 'Invalid category slugs should be rejected.');
$updatedCategory = $categories->update(['id' => $category['id']], ['name' => 'Announcements', 'slug' => 'announcements']);
assertBlog($updatedCategory === true, 'An existing category should update.');
assertBlog($categories->destroy($category['id']) === true, 'A category should be deleted.');
assertBlog($posts->findWithId($secondPost['id'])['category_id'] === null, 'Deleting a category should detach its posts.');
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($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.');
fwrite(STDOUT, "Blog repository tests passed.\n");