improve publishing
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
use Plugi\Core\DB;
|
||||
use Plugi\Contracts\PageContract;
|
||||
use Plugi\Contracts\PageTranslationContract;
|
||||
use Plugi\Core\Csrf;
|
||||
use Plugi\Modules\GrapesJS\PageBuilder;
|
||||
use Plugi\Modules\Router\DatabasePageRouter;
|
||||
use Plugi\Page;
|
||||
@@ -21,10 +22,12 @@ require_once __DIR__ . '/../src/Contracts/PageBuilderContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/ThemeContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/SettingRepositoryContract.php';
|
||||
require_once __DIR__ . '/../src/Contracts/SettingContract.php';
|
||||
require_once __DIR__ . '/../src/Core/Csrf.php';
|
||||
require_once __DIR__ . '/../src/Core/DB.php';
|
||||
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
|
||||
require_once __DIR__ . '/../src/Repositories/SettingRepository.php';
|
||||
require_once __DIR__ . '/../src/Repositories/PageTranslationRepository.php';
|
||||
require_once __DIR__ . '/../src/Repositories/PageDraftPublishedCacheInvalidationException.php';
|
||||
require_once __DIR__ . '/../src/PageTranslationService.php';
|
||||
require_once __DIR__ . '/../src/Page.php';
|
||||
require_once __DIR__ . '/../src/PageTranslation.php';
|
||||
@@ -55,6 +58,7 @@ class PageCreationTestDatabase extends DB
|
||||
public ?string $failOnDeleteTable = null;
|
||||
public bool $throwOnDeleteFailure = false;
|
||||
public bool $failOnPageUpdate = false;
|
||||
public ?int $failOnPageUpdateId = null;
|
||||
public array $schemaDiffs = [];
|
||||
|
||||
public function __construct()
|
||||
@@ -75,6 +79,9 @@ class PageCreationTestDatabase extends DB
|
||||
if ($this->failOnPageUpdate && str_starts_with($query, 'UPDATE pages SET')) {
|
||||
return false;
|
||||
}
|
||||
if ($this->failOnPageUpdateId !== null && str_starts_with($query, 'UPDATE pages SET') && (int) end($parameters) === $this->failOnPageUpdateId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (str_starts_with($query, 'INSERT INTO page_translations')) {
|
||||
$this->translationInsertCount++;
|
||||
@@ -89,6 +96,18 @@ class PageCreationTestDatabase extends DB
|
||||
return parent::query($query, $parameters);
|
||||
}
|
||||
|
||||
public function queryAffectedRows(string $query, array $parameters = []): int|false
|
||||
{
|
||||
if ($this->failOnPageUpdate && str_starts_with($query, 'UPDATE pages SET')) {
|
||||
return false;
|
||||
}
|
||||
if ($this->failOnPageUpdateId !== null && str_starts_with($query, 'UPDATE pages SET') && (int) end($parameters) === $this->failOnPageUpdateId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return parent::queryAffectedRows($query, $parameters);
|
||||
}
|
||||
|
||||
public function all(string $table, array|string $columns = '*'): array
|
||||
{
|
||||
if ($table === 'page_translations') {
|
||||
@@ -225,9 +244,13 @@ class PageCreationTestCache
|
||||
public static array $cacheReads = [];
|
||||
public static array $cacheWrites = [];
|
||||
public static ?string $cachedContent = null;
|
||||
public static bool $throwOnInvalidate = false;
|
||||
|
||||
public function invalidate(string $route): void
|
||||
{
|
||||
if (self::$throwOnInvalidate) {
|
||||
throw new RuntimeException('Simulated route cache invalidation failure.');
|
||||
}
|
||||
self::$invalidatedRoutes[] = $route;
|
||||
}
|
||||
|
||||
@@ -386,6 +409,8 @@ function phpb_static(string $name): string
|
||||
|
||||
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
|
||||
{
|
||||
global $pageCreationRedirectFlash;
|
||||
$pageCreationRedirectFlash = $flashData;
|
||||
throw new PageCreationRedirectException($url);
|
||||
}
|
||||
|
||||
@@ -398,6 +423,11 @@ function phpb_csrf_field(): void
|
||||
{
|
||||
}
|
||||
|
||||
function phpb_validate_csrf(): bool
|
||||
{
|
||||
return Csrf::validateToken($_POST['_csrf_token'] ?? '');
|
||||
}
|
||||
|
||||
function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]): void
|
||||
{
|
||||
global $phpb_db, $pageCreationConfig, $pageCreationLanguages;
|
||||
@@ -422,6 +452,7 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
|
||||
PageCreationTestCache::$invalidatedRoutes = [];
|
||||
PageCreationTestCache::$cacheReads = [];
|
||||
PageCreationTestCache::$cacheWrites = [];
|
||||
PageCreationTestCache::$throwOnInvalidate = false;
|
||||
$phpb_db = new PageCreationTestDatabase();
|
||||
$phpb_db->createSchema();
|
||||
}
|
||||
@@ -440,6 +471,25 @@ function pageCreationPayload(array $overrides = []): array
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
function pageCreationAddDraft(PageRepository $repository, string $name, string $route): PageContract
|
||||
{
|
||||
if (! $repository->create(pageCreationPayload([
|
||||
'name' => $name,
|
||||
'route' => ['en' => $route, 'de' => '/de' . $route],
|
||||
]))) {
|
||||
throw new RuntimeException('Could not create a page for the batch publishing test.');
|
||||
}
|
||||
|
||||
global $phpb_db;
|
||||
$rows = $phpb_db->rows('pages');
|
||||
$page = $repository->findWithId($rows[array_key_last($rows)]['id']);
|
||||
if (! ($page instanceof PageContract) || ! $repository->updatePageDraftData($page, ['html' => ['<p>Draft</p>']])) {
|
||||
throw new RuntimeException('Could not save a draft for the batch publishing test.');
|
||||
}
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
function assertPageCreation(bool $condition, string $message): void
|
||||
{
|
||||
if (! $condition) {
|
||||
@@ -962,6 +1012,122 @@ $cases = [
|
||||
'The pages schema does not declare a nullable draft_data column.'
|
||||
);
|
||||
},
|
||||
'publishing a stale page snapshot preserves the newer draft' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
$page = pageCreationAddDraft($repository, 'Concurrent page', '/concurrent');
|
||||
global $phpb_db;
|
||||
$stalePage = $repository->findWithId($page->getId());
|
||||
$newerDraft = ['html' => ['<p>Newer draft</p>']];
|
||||
assertPageCreation($repository->updatePageDraftData($page, $newerDraft), 'The newer draft could not be saved.');
|
||||
|
||||
assertPageCreation($repository->publishPageDraft($stalePage) === false, 'Publishing a stale draft snapshot was not reported as a conflict.');
|
||||
$pageRow = $phpb_db->rows('pages')[0];
|
||||
assertPageCreation($pageRow['draft_data'] === json_encode($newerDraft), 'Publishing a stale draft snapshot erased the newer draft.');
|
||||
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'A stale draft snapshot invalidated the page cache.');
|
||||
},
|
||||
'website manager batch publishing promotes every valid draft' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
pageCreationAddDraft($repository, 'First page', '/first');
|
||||
pageCreationAddDraft($repository, 'Second page', '/second');
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = ['_csrf_token' => 'publish-token'];
|
||||
$_SESSION = ['phpb_csrf_tokens' => ['publish-token' => time()]];
|
||||
|
||||
$result = (new WebsiteManager())->handlePublishAllDrafts();
|
||||
|
||||
assertPageCreation($result === ['total' => 2, 'published' => ['First page', 'Second page'], 'failed' => [], 'cache_warnings' => []], 'Batch publication did not report all successful pages.');
|
||||
global $phpb_db;
|
||||
foreach ($phpb_db->rows('pages') as $pageRow) {
|
||||
assertPageCreation(json_decode($pageRow['data'], true) === ['html' => ['<p>Draft</p>']], 'Batch publication did not promote a page draft.');
|
||||
assertPageCreation($pageRow['draft_data'] === null, 'Batch publication did not clear a successfully published draft.');
|
||||
}
|
||||
assertPageCreation(count(PageCreationTestCache::$invalidatedRoutes) === 4, 'Batch publication did not invalidate routes for both published pages.');
|
||||
},
|
||||
'website manager batch publishing reports partial failures and preserves failed drafts' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
$firstPage = pageCreationAddDraft($repository, 'First page', '/first');
|
||||
$secondPage = pageCreationAddDraft($repository, 'Second page', '/second');
|
||||
global $phpb_db, $pageCreationRedirectFlash;
|
||||
$phpb_db->failOnPageUpdateId = (int) $secondPage->getId();
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = ['_csrf_token' => 'publish-token'];
|
||||
$_SESSION = ['phpb_csrf_tokens' => ['publish-token' => time()]];
|
||||
$pageCreationRedirectFlash = [];
|
||||
|
||||
try {
|
||||
(new WebsiteManager())->handleRequest('drafts', 'publish_all');
|
||||
throw new RuntimeException('Batch publishing did not redirect after completion.');
|
||||
} catch (PageCreationRedirectException $exception) {
|
||||
assertPageCreation($exception->redirectUrl === '/website_manager', 'Batch publishing redirected to an unexpected page.');
|
||||
}
|
||||
|
||||
assertPageCreation($pageCreationRedirectFlash['message-type'] === 'warning', 'Partial batch failure did not produce a warning.');
|
||||
assertPageCreation(str_contains($pageCreationRedirectFlash['message'], 'Second page'), 'Partial batch feedback did not identify the failed page.');
|
||||
assertPageCreation(str_contains($pageCreationRedirectFlash['message'], 'remain available to retry'), 'Partial batch feedback did not explain that failed drafts are retained.');
|
||||
$rowsById = [];
|
||||
foreach ($phpb_db->rows('pages') as $pageRow) {
|
||||
$rowsById[(int) $pageRow['id']] = $pageRow;
|
||||
}
|
||||
assertPageCreation($rowsById[(int) $firstPage->getId()]['draft_data'] === null, 'The successful page draft was not cleared.');
|
||||
assertPageCreation($rowsById[(int) $secondPage->getId()]['draft_data'] !== null, 'The failed page draft was not preserved for retry.');
|
||||
assertPageCreation(count(PageCreationTestCache::$invalidatedRoutes) === 2, 'Partial batch failure invalidated routes for a failed page.');
|
||||
},
|
||||
'website manager reports a published page when cache invalidation fails' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
pageCreationAddDraft($repository, 'Cached page', '/cached');
|
||||
global $phpb_db, $pageCreationRedirectFlash;
|
||||
PageCreationTestCache::$throwOnInvalidate = true;
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = ['_csrf_token' => 'publish-token'];
|
||||
$_SESSION = ['phpb_csrf_tokens' => ['publish-token' => time()]];
|
||||
$pageCreationRedirectFlash = [];
|
||||
|
||||
try {
|
||||
(new WebsiteManager())->handleRequest('drafts', 'publish_all');
|
||||
throw new RuntimeException('Batch publishing did not redirect after completion.');
|
||||
} catch (PageCreationRedirectException $exception) {
|
||||
assertPageCreation($exception->redirectUrl === '/website_manager', 'Batch publishing redirected to an unexpected page.');
|
||||
}
|
||||
|
||||
assertPageCreation($pageCreationRedirectFlash['message-type'] === 'warning', 'A post-save cache failure was not reported as a warning.');
|
||||
assertPageCreation(str_contains($pageCreationRedirectFlash['message'], 'Published changes for 1'), 'Cache invalidation failure was reported as an unpublished page.');
|
||||
assertPageCreation(str_contains($pageCreationRedirectFlash['message'], 'Cached page'), 'Cache warning did not identify the published page.');
|
||||
$pageRow = $phpb_db->rows('pages')[0];
|
||||
assertPageCreation($pageRow['draft_data'] === null, 'The published draft remained after cache invalidation failed.');
|
||||
assertPageCreation(json_decode($pageRow['data'], true) === ['html' => ['<p>Draft</p>']], 'The saved draft was not published before cache invalidation failed.');
|
||||
},
|
||||
'website manager batch publishing handles the no-draft state' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_POST = ['_csrf_token' => 'publish-token'];
|
||||
$_SESSION = ['phpb_csrf_tokens' => ['publish-token' => time()]];
|
||||
|
||||
$result = (new WebsiteManager())->handlePublishAllDrafts();
|
||||
|
||||
assertPageCreation($result === ['total' => 0, 'published' => [], 'failed' => [], 'cache_warnings' => []], 'An empty batch returned unexpected publication results.');
|
||||
},
|
||||
'website manager batch publishing rejects missing and invalid CSRF tokens' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
pageCreationAddDraft($repository, 'Protected page', '/protected');
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
$_SESSION = ['phpb_csrf_tokens' => ['valid-token' => time()]];
|
||||
http_response_code(200);
|
||||
|
||||
$_POST = [];
|
||||
assertPageCreation((new WebsiteManager())->handlePublishAllDrafts() === null, 'Batch publication accepted a missing CSRF token.');
|
||||
assertPageCreation(http_response_code() === 403, 'Missing CSRF token did not receive a forbidden response.');
|
||||
|
||||
$_POST = ['_csrf_token' => 'invalid-token'];
|
||||
assertPageCreation((new WebsiteManager())->handlePublishAllDrafts() === null, 'Batch publication accepted an invalid CSRF token.');
|
||||
global $phpb_db;
|
||||
assertPageCreation($phpb_db->rows('pages')[0]['draft_data'] !== null, 'Rejected CSRF requests changed the saved draft.');
|
||||
http_response_code(200);
|
||||
},
|
||||
'public requests show drafts only for authenticated session-bound preview tokens' => function (): void {
|
||||
resetPageCreationDatabase();
|
||||
$repository = new PageRepository();
|
||||
|
||||
Reference in New Issue
Block a user