Files
plugi/extensions/plugi-ext-blog/tests/BlogPreviewRouteTest.php
T
deepDiverPaul 8ebed89e73 feat(ext-blog): Add syntax highlighting for code blocks
Added language-specific syntax highlighting support to the markdown editor and preview. New code-highlighter assets are registered for public pages and admin headers. The PostContentRenderer detects language identifiers in code fences to apply appropriate CSS classes for highlighting. Tests verify the highlighting works correctly and unsafe content is escaped properly.
2026-12-02 11:09:09 +01:00

118 lines
5.0 KiB
PHP

<?php
namespace Plugi\Extensions\Blog {
class PostsRepository
{
public static int $instances = 0;
public function __construct()
{
self::$instances++;
throw new \RuntimeException('Preview must not access the posts repository.');
}
}
}
namespace {
require_once dirname(__DIR__) . '/admin/Classes/PostContentRenderer.php';
function assertPreviewRoute(bool $condition, string $message): void
{
if (!$condition) {
throw new RuntimeException($message);
}
}
$previewMarkdown = "## Preview\n\nSafe **source**.\n\n- list item\n\n---\n\n> Quoted text.\n\n```php\n<code>safe</code>\n```\n\n~~~php\" onclick=\"alert(1)\n<script>alert(1)</script>\n~~~";
if (($argv[1] ?? '') === '--child') {
$scenario = $argv[2] ?? '';
$GLOBALS['previewAuthenticated'] = $scenario !== 'unauthenticated';
$GLOBALS['previewCsrfValid'] = $scenario !== 'invalid-csrf';
function phpb_requires_authenticated(): void
{
if (!$GLOBALS['previewAuthenticated']) {
http_response_code(403);
exit();
}
}
function phpb_validate_csrf(): bool
{
return $GLOBALS['previewCsrfValid'];
}
register_shutdown_function(static function (): void {
echo "\n__STATUS__" . http_response_code() . "\n";
echo '__REPOSITORY_INSTANTIATIONS__' . \Plugi\Extensions\Blog\PostsRepository::$instances . "\n";
});
$_SERVER['REQUEST_METHOD'] = $scenario === 'non-post' ? 'GET' : 'POST';
$_POST = match ($scenario) {
'invalid-body' => ['body' => ['not', 'markdown']],
'oversized-body' => ['body' => str_repeat('x', 1000001)],
default => ['body' => $previewMarkdown],
};
include dirname(__DIR__) . '/routes/previewPost.php';
exit();
}
function requestPreviewRoute(string $scenario): array
{
$process = proc_open(
[PHP_BINARY, __FILE__, '--child', $scenario],
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
$pipes,
dirname(__DIR__, 3)
);
if (!is_resource($process)) {
throw new RuntimeException('Could not start the preview route test process.');
}
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
if ($exitCode !== 0 || !preg_match('/\n__STATUS__(\d+)\n__REPOSITORY_INSTANTIATIONS__(\d+)\n$/', $output, $matches)) {
throw new RuntimeException('Preview route subprocess failed: ' . $error . $output);
}
$responseLength = strpos($output, "\n__STATUS__");
return [
'status' => (int) $matches[1],
'repository_instances' => (int) $matches[2],
'body' => substr($output, 0, $responseLength),
];
}
foreach ([
'unauthenticated' => 403,
'non-post' => 405,
'invalid-csrf' => 403,
'invalid-body' => 400,
'oversized-body' => 413,
] as $scenario => $expectedStatus) {
$response = requestPreviewRoute($scenario);
assertPreviewRoute($response['status'] === $expectedStatus, 'The preview route should reject ' . $scenario . ' requests.');
assertPreviewRoute($response['repository_instances'] === 0, 'Rejected preview requests must not access saved posts.');
if ($scenario !== 'unauthenticated') {
$payload = json_decode($response['body'], true);
assertPreviewRoute(is_array($payload) && isset($payload['error']), 'Rejected preview requests should return a JSON error.');
}
}
$response = requestPreviewRoute('valid');
$payload = json_decode($response['body'], true);
$expectedHtml = (new \Plugi\Extensions\Blog\PostContentRenderer())->render($previewMarkdown);
assertPreviewRoute($response['status'] === 200, 'A valid preview request should succeed.');
assertPreviewRoute($payload === ['html' => $expectedHtml], 'The preview should return shared renderer output as JSON.');
assertPreviewRoute(str_contains($payload['html'], '<ul class="list-disc') && str_contains($payload['html'], '<hr class="my-6 border-base-300">') && str_contains($payload['html'], '<blockquote') && str_contains($payload['html'], '<pre'), 'The live preview should render lists, horizontal rules, quotes, and code blocks.');
assertPreviewRoute(str_contains($payload['html'], '<code class="language-php">&lt;code&gt;safe&lt;/code&gt;</code>') && str_contains($payload['html'], '<code>&lt;script&gt;alert(1)&lt;/script&gt;</code>') && !str_contains($payload['html'], 'onclick='), 'The preview should keep safe language metadata, reject malformed labels, and escape code.');
assertPreviewRoute($response['repository_instances'] === 0, 'Preview rendering must not read or write saved posts.');
fwrite(STDOUT, "Blog preview route tests passed.\n");
}