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, featured_image_id VARCHAR(50) 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_uploads ( id INTEGER PRIMARY KEY AUTOINCREMENT, public_id VARCHAR(50) NOT NULL UNIQUE, original_file VARCHAR(512) NOT NULL, mime_type VARCHAR(50) NOT NULL, server_file VARCHAR(512) NOT NULL, alt_text VARCHAR(1000) NOT NULL DEFAULT "", folder VARCHAR(255) NOT NULL DEFAULT "" )'); $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'); } function renderBlogAdminList(): string { ob_start(); include dirname(__DIR__) . '/admin/Views/ListPosts.php'; return (string) ob_get_clean(); } function renderBlogEditor(int $postId): string { $_GET = ['id' => (string) $postId]; ob_start(); include dirname(__DIR__) . '/admin/Views/EditPost.php'; return (string) ob_get_clean(); } $_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(in_array('/admin/assets/markdown-editor.js', array_column($blogConfig['assets'], 'src'), true) && in_array('/admin/assets/markdown-editor.css', array_column($blogConfig['assets'], 'src'), true), 'The editor script and stylesheet should be registered as extension assets.'); $publicAssets = array_values(array_filter($blogConfig['assets'], fn(array $asset): bool => $asset['location'] === 'footer')); $adminAssets = array_values(array_filter($blogConfig['assets'], fn(array $asset): bool => $asset['location'] === 'admin-header')); assertBlog(in_array(['src' => '/assets/code-highlighter.css', 'type' => 'style', 'location' => 'footer'], $publicAssets, true) && in_array(['src' => '/assets/code-highlighter.js', 'type' => 'script', 'location' => 'footer'], $publicAssets, true), 'The highlighter assets should be registered for public pages.'); assertBlog(in_array(['src' => '/assets/code-highlighter.css', 'type' => 'style', 'location' => 'admin-header'], $adminAssets, true) && in_array(['src' => '/assets/code-highlighter.js', 'type' => 'script', 'location' => 'admin-header'], $adminAssets, true), 'The highlighter assets should be registered for admin pages.'); assertBlog(array_search('/assets/code-highlighter.js', array_column($adminAssets, 'src'), true) < array_search('/admin/assets/markdown-editor.js', array_column($adminAssets, 'src'), true), 'The admin highlighter should load before the Markdown editor.'); $highlighterSource = file_get_contents(dirname(__DIR__) . '/assets/src/code-highlighter.js'); $editorSource = file_get_contents(dirname(__DIR__) . '/admin/assets/src/markdown-editor.js'); assertBlog(str_contains($highlighterSource, 'highlightPage') && str_contains($highlighterSource, "document.addEventListener('DOMContentLoaded'"), 'The highlighter should initialize code blocks on initial page content.'); assertBlog(str_contains($editorSource, 'window.blogCodeHighlighter?.highlight(preview)'), 'The editor should highlight preview code after replacing its contents.'); assertBlog(count(array_intersect(['/ext--blog/save-post', '/ext--blog/preview-post', '/ext--blog/delete-post', '/ext--blog/save-category', '/ext--blog/delete-category'], array_keys(\Plugi\Extensions::getRoutes()))) === 5, 'Blog post and category 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.'); $phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [ 'blog-cover-1', 'cover.jpg', 'image/jpeg', 'cover.jpg', 'A "featured" & ', ]); $phpb_db->query('INSERT INTO test_uploads (public_id, original_file, mime_type, server_file, alt_text) VALUES (?, ?, ?, ?, ?)', [ 'blog-document-1', 'notes.pdf', 'application/pdf', 'notes.pdf', 'A document', ]); $post = $posts->create([ 'title' => 'First post', 'slug' => 'first-post', 'excerpt' => 'A short summary', 'body' => 'Post body', 'featured_image_id' => 'blog-cover-1', '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.'); assertBlog($post['featured_image_id'] === 'blog-cover-1', 'A valid image upload reference should be persisted on the post.'); expectBlogValidation(fn() => $posts->create([ 'title' => 'Missing featured image', 'slug' => 'missing-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'missing-upload', 'category_id' => '', 'status' => 'draft', 'published_at' => '', ]), 'Missing upload references should be rejected.'); expectBlogValidation(fn() => $posts->create([ 'title' => 'Non-image featured image', 'slug' => 'non-image-featured-image', 'excerpt' => '', 'body' => 'Body', 'featured_image_id' => 'blog-document-1', 'category_id' => '', 'status' => 'draft', 'published_at' => '', ]), 'Non-image upload references should be rejected.'); $olderPost = $posts->create([ 'title' => 'Older published post', 'slug' => 'older-published-post', 'excerpt' => 'Older excerpt', 'body' => "## Markdown heading\n\nA **bold** and *emphasized* phrase with `inline code`, a [safe link](https://example.com), an [unsafe link](javascript:alert), and an [encoded unsafe link](javascript:alert).\n\n- first item\n- second item\n\n1. first numbered item\n2. second numbered item\n\n![Inline & ]](https://images.example/photo.jpg)\n![Unsafe JavaScript](javascript:alert)\n![Encoded JavaScript](javascript:alert)\n![Unsafe data](data:text/html;base64,abc)\n\n&safe\n\n---\n\n> Quoted **text**.\n\n```php\n\n```\n\n~~~php\" onmouseover=\"alert(1)\n\n~~~", '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' => '', ]); $_ENV['BASE_URL'] = 'https://blog.example'; $phpb_config = ['website_manager' => ['url' => '/website-manager'], 'general' => ['uploads_url' => '/uploads']]; $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.'); $editorHtml = renderBlogEditor((int) $post['id']); assertBlog(str_contains($editorHtml, '