Dev #8

Merged
deepDiverPaul merged 14 commits from dev into main 2026-11-26 09:04:24 +00:00
19 changed files with 983 additions and 122 deletions
Showing only changes of commit a07e3ad8d9 - Show all commits
+1
View File
@@ -33,6 +33,7 @@ return [
'page-create-failed' => 'Die Seite konnte nicht erstellt werden. Prüfen Sie Pflichtfelder, übersetzte Werte, Routen und die Datenbankverbindung und versuchen Sie es erneut.',
'page-updated' => 'Seite aktualisiert',
'page-deleted' => 'Seite gelöscht',
'page-delete-failed' => 'Die Seite konnte nicht gelöscht werden. Versuchen Sie es erneut oder prüfen Sie die Datenbankverbindung.',
'page-type' => 'Seitentyp',
'page-types' => [
'static' => 'Statische Seite',
+1
View File
@@ -33,6 +33,7 @@ return [
'page-create-failed' => 'Page could not be created. Check required fields, localized values, routes, and the database connection, then try again.',
'page-updated' => 'Page successfully updated',
'page-deleted' => 'Page removed',
'page-delete-failed' => 'Page could not be deleted. Try again or check the database connection.',
'page-type' => 'Page type',
'page-types' => [
'static' => 'Static page',
+1
View File
@@ -32,6 +32,7 @@ return [
'page-created' => 'Sidan har skapats',
'page-updated' => 'Sidan har uppdaterats',
'page-deleted' => 'Sidan har tagits bort',
'page-delete-failed' => 'Sidan kunde inte tas bort. Försök igen eller kontrollera databasanslutningen.',
'page-type' => 'Sidtyp',
'page-types' => [
'static' => 'Statisk sida',
@@ -4,4 +4,20 @@ namespace Plugi\Contracts;
interface PageTranslationRepositoryContract
{
/**
* Determine whether a route is already used by another page translation.
*
* @param string $route
* @param mixed|null $excludedPageId
* @return bool
*/
public function routeExists(string $route, $excludedPageId = null): bool;
/**
* Return translations belonging to the given page IDs.
*
* @param array $pageIds
* @return array
*/
public function getForPages(array $pageIds): array;
}
@@ -8,6 +8,7 @@ use Plugi\Contracts\ThemeContract;
use Plugi\Modules\GrapesJS\Block\BlockAdapter;
use Plugi\Modules\GrapesJS\Thumb\ThumbGenerator;
use Plugi\Modules\GrapesJS\Upload\Uploader;
use Plugi\PageTranslationService;
use Plugi\Repositories\PageRepository;
use Plugi\Repositories\UploadRepository;
use Exception;
@@ -101,14 +102,22 @@ class PageBuilder implements PageBuilderContract
}
break;
case 'renderBlock':
if (isset($_POST['language']) && isset($_POST['data']) && isset(phpb_active_languages()[$_POST['language']])) {
$this->renderPageBuilderBlock($page, $_POST['language'], json_decode($_POST['data'], true));
$language = $this->getValidPostedLanguage();
if ($language === null) {
$this->respondToInvalidLanguageRequest();
}
if (isset($_POST['data'])) {
$this->renderPageBuilderBlock($page, $language, json_decode($_POST['data'], true));
exit();
}
break;
case 'renderLanguageVariant':
if (isset($_POST['language']) && isset($_POST['data']) && isset(phpb_active_languages()[$_POST['language']])) {
$this->renderLanguageVariant($page, $_POST['language'], json_decode($_POST['data'], true));
$language = $this->getValidPostedLanguage();
if ($language === null) {
$this->respondToInvalidLanguageRequest();
}
if (isset($_POST['data'])) {
$this->renderLanguageVariant($page, $language, json_decode($_POST['data'], true));
exit();
}
break;
@@ -204,8 +213,13 @@ class PageBuilder implements PageBuilderContract
// init variables that should be accessible in the view
$pageBuilder = $this;
$pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page, true]);
if (! empty($_SESSION['plugi_language'])) {
$pageRenderer->setLanguage($_SESSION['plugi_language']);
$activeLanguages = array_keys(phpb_active_languages());
$currentLanguage = (new PageTranslationService())->resolveLocale($_SESSION['plugi_language'] ?? null, $activeLanguages);
if ($currentLanguage !== null) {
$_SESSION['plugi_language'] = $currentLanguage;
$pageRenderer->setLanguage($currentLanguage);
} else {
unset($_SESSION['plugi_language']);
}
// create an array of theme blocks and theme block settings for in the page builder sidebar
@@ -279,6 +293,9 @@ class PageBuilder implements PageBuilderContract
public function renderLanguageVariant(PageContract $page, string $language, $blockData = [])
{
phpb_set_in_editmode();
if (! (new PageTranslationService())->isAvailableLocale($language, array_keys(phpb_active_languages()))) {
$this->respondToInvalidLanguageRequest();
}
$_SESSION['plugi_language'] = $language;
$blockData = is_array($blockData) ? $blockData : [];
@@ -291,6 +308,32 @@ class PageBuilder implements PageBuilderContract
]);
}
/**
* Return the requested language only when it is an active locale.
*
* @return string|null
*/
protected function getValidPostedLanguage(): ?string
{
$language = $_POST['language'] ?? null;
if (! is_string($language) || ! (new PageTranslationService())->isAvailableLocale($language, array_keys(phpb_active_languages()))) {
return null;
}
return $language;
}
/**
* Return a clear client error for an unsupported language request.
*/
protected function respondToInvalidLanguageRequest(): void
{
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['message' => 'Unsupported language.']);
exit();
}
/**
* Update the given page with the given data (an array of html blocks).
*
@@ -5,6 +5,7 @@ namespace Plugi\Modules\GrapesJS;
use Plugi\Contracts\PageContract;
use Plugi\Contracts\ThemeContract;
use Plugi\Modules\GrapesJS\Block\BlockRenderer;
use Plugi\PageTranslationService;
use Plugi\ThemeBlock;
use Exception;
use Plugi\Extensions;
@@ -93,9 +94,7 @@ class PageRenderer
}
}
if ($blockKeysAreLanguages) {
if (! in_array($language, $supportedLanguages)) {
$language = $supportedLanguages[0] ?? $language;
}
$language = (new PageTranslationService())->resolveLocale($language, $supportedLanguages) ?? $language;
}
$this->language = $language;
@@ -78,8 +78,12 @@
if (!select) return;
let selectedLanguage = select.value;
window.switchLanguage(selectedLanguage, function() {
window.switchLanguage(selectedLanguage, function(success) {
if (success) {
activateLanguage(selectedLanguage);
} else {
select.value = window.currentLanguage;
}
});
});
@@ -74,7 +74,7 @@
errorMessage = errData.message ? (errorMessage + ': "' + errData.message + '"') : errorMessage;
window.toastr.error(errorMessage);
window.toastr.error(window.translations['toastr-switching-language-failed']);
callback();
callback(false);
window.setWaiting(false);
return;
}
@@ -82,10 +82,10 @@
const responseText = await response.text();
let parsed = JSON.parse(responseText);
window.pageBlocks[newLanguage] = parsed.dynamicBlocks ? parsed.dynamicBlocks : {};
callback();
callback(true);
window.setWaiting(false);
} catch (error) {
callback();
callback(false);
console.error(error);
window.toastr.error(error.message || 'Error');
window.toastr.error(window.translations['toastr-switching-language-failed']);
@@ -95,81 +95,70 @@
};
/**
* Copy new blocks of the current language to the new language or remove old blocks from the new language.
* Copy new shared blocks of the current language to the new language.
*
* @param newLanguage
*/
function applyChangesFromCurrentLanguageToNewLanguage(newLanguage) {
let newLanguageBlocks = window.pageBlocks[newLanguage];
let currentLanguageBlocks = window.pageBlocks[window.currentLanguage];
if (newLanguageBlocks === undefined) {
newLanguageBlocks = currentLanguageBlocks;
} else {
updateNestedBlocks(currentLanguageBlocks, newLanguageBlocks);
// copy missing blocks from the current language to the target language
for (let blockId in currentLanguageBlocks) {
if (newLanguageBlocks[blockId] === undefined) {
newLanguageBlocks[blockId] = currentLanguageBlocks[blockId];
}
}
}
// copy the content of blocks containers of the current language to the blocks containers of the new language
for (let blockId in currentLanguageBlocks) {
let currentBlockHtml = (currentLanguageBlocks[blockId] && currentLanguageBlocks[blockId]['html']) || '';
let newBlockHtml = (newLanguageBlocks[blockId] && newLanguageBlocks[blockId]['html']) || '';
let currDiv = document.createElement("div");
currDiv.innerHTML = currentBlockHtml;
let newDiv = document.createElement("div");
newDiv.innerHTML = newBlockHtml;
let currContainers = currDiv.querySelectorAll("[phpb-blocks-container]");
let newContainers = newDiv.querySelectorAll("[phpb-blocks-container]");
currContainers.forEach((cont, index) => {
if (newContainers[index]) {
newContainers[index].innerHTML = cont.innerHTML;
}
});
newLanguageBlocks[blockId]['html'] = newDiv.innerHTML;
}
window.pageBlocks[newLanguage] = newLanguageBlocks;
const currentLanguageBlocks = window.pageBlocks[window.currentLanguage] || {};
window.pageBlocks[newLanguage] = window.synchronizePageBlockVariants(
currentLanguageBlocks,
window.pageBlocks[newLanguage] || {}
);
}
/**
* Replace phpb-blocks-container html snippets if a block of the current language already exists in the target language.
* This ensures all child blocks are present for all languages and they remain in the same order
* Synchronize shared block structure without replacing existing locale-specific block data.
*/
function updateNestedBlocks(currentLanguageBlocks, newLanguageBlocks) {
for (let blockId in currentLanguageBlocks) {
// skip if the parent block does not yet exist in the target language
if (newLanguageBlocks[blockId] === undefined) {
continue;
window.synchronizePageBlockVariants = function(sourceBlocks, targetBlocks) {
sourceBlocks = sourceBlocks && typeof sourceBlocks === 'object' ? sourceBlocks : {};
targetBlocks = targetBlocks && typeof targetBlocks === 'object' && !Array.isArray(targetBlocks) ? targetBlocks : {};
Object.keys(sourceBlocks).forEach(blockId => {
const sourceBlock = sourceBlocks[blockId];
const targetBlock = targetBlocks[blockId];
if (! targetBlock || typeof targetBlock !== 'object') {
targetBlocks[blockId] = JSON.parse(JSON.stringify(sourceBlock));
return;
}
for (let subBlockId in currentLanguageBlocks[blockId].blocks) {
let updatedSubBlock = currentLanguageBlocks[blockId].blocks[subBlockId];
let oldSubBlock = newLanguageBlocks[blockId].blocks[subBlockId];
if (! updatedSubBlock || ! oldSubBlock) {
continue;
if (typeof sourceBlock?.html === 'string' && typeof targetBlock.html === 'string') {
targetBlock.html = synchronizeBlockContainers(sourceBlock.html, targetBlock.html);
}
let updatedSubBlockMatches = updatedSubBlock.html.match(/phpb-blocks-container(.*)>(.*)</g);
let oldSubBlockMatches = oldSubBlock.html.match(/phpb-blocks-container(.*)>(.*)</g);
if (! updatedSubBlockMatches || ! oldSubBlockMatches) {
continue;
if (sourceBlock?.blocks && typeof sourceBlock.blocks === 'object') {
targetBlock.blocks = window.synchronizePageBlockVariants(sourceBlock.blocks, targetBlock.blocks || {});
}
});
return targetBlocks;
};
/**
* Copy only shared child structure from the source language into existing block containers.
*/
function synchronizeBlockContainers(sourceHtml, targetHtml) {
if (! sourceHtml.includes('phpb-blocks-container')) {
return targetHtml;
}
for (let i = 0; i < updatedSubBlockMatches.length; i++) {
newLanguageBlocks[blockId].blocks[subBlockId].html =
newLanguageBlocks[blockId].blocks[subBlockId].html.replace(oldSubBlockMatches[i], updatedSubBlockMatches[i]);
}
}
const sourceElement = document.createElement('div');
sourceElement.innerHTML = sourceHtml;
const targetElement = document.createElement('div');
targetElement.innerHTML = targetHtml;
const sourceContainers = sourceElement.querySelectorAll('[phpb-blocks-container]');
const targetContainers = targetElement.querySelectorAll('[phpb-blocks-container]');
sourceContainers.forEach((sourceContainer, index) => {
if (targetContainers[index]) {
targetContainers[index].innerHTML = sourceContainer.innerHTML;
} else {
targetElement.appendChild(sourceContainer.cloneNode(true));
}
});
return targetElement.innerHTML;
}
/**
@@ -18,13 +18,6 @@
<script type="text/javascript" src="<?= phpb_asset('pagebuilder/grapesjs-touch-v0.1.1.min.js') ?>"></script>
<script type="text/javascript">
<?php
$currentLanguage = in_array(phpb_config('general.language'), phpb_active_languages()) ?
phpb_config('general.language') : array_keys(phpb_active_languages())[0];
if (! empty($_SESSION['plugi_language'])) {
$currentLanguage = $_SESSION['plugi_language'];
}
?>
window.languages = <?= json_encode(phpb_active_languages()) ?>;
window.currentLanguage = <?= json_encode($currentLanguage) ?>;
window.translations = <?= json_encode(phpb_trans('pagebuilder')) ?>;
@@ -5,9 +5,9 @@ namespace Plugi\Modules\WebsiteManager;
use Plugi\Contracts\PageContract;
use Plugi\Contracts\WebsiteManagerContract;
use Plugi\Extensions;
use Plugi\PageTranslationService;
use Plugi\Repositories\MenuRepository;
use Plugi\Repositories\PageRepository;
use Plugi\Repositories\PageTranslationRepository;
use Plugi\Repositories\SettingRepository;
use Plugi\Repositories\UploadRepository;
@@ -127,7 +127,12 @@ class WebsiteManager implements WebsiteManagerContract
public function handleDestroy(PageContract $page)
{
$pageRepository = new PageRepository;
$pageRepository->destroy($page->getId());
if (! $pageRepository->destroy($page->getId())) {
phpb_redirect(phpb_url('website_manager'), [
'message-type' => 'error',
'message' => phpb_trans('website-manager.page-delete-failed')
]);
}
phpb_redirect(phpb_url('website_manager'), [
'message-type' => 'success',
'message' => phpb_trans('website-manager.page-deleted')
@@ -194,8 +199,8 @@ class WebsiteManager implements WebsiteManagerContract
return ($a->getRoute() < $b->getRoute()) ? -1 : 1;
});
$pageTranslationRepository = new PageTranslationRepository;
$pageTranslations = $pageTranslationRepository->getAll();
$activeLanguages = phpb_active_languages();
$pageTranslationCoverage = (new PageTranslationService())->getPageCoverage($pages, $activeLanguages);
$filesRepository = new UploadRepository;
$files = $filesRepository->getAll();
@@ -104,7 +104,7 @@ $javascriptValue = static function (string $value): string {
<div class="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between">
<div>
<h2 class="text-lg font-semibold text-base-content">Localized page details</h2>
<p class="text-sm text-base-content/60">Titles, routes, and metadata can vary by language.</p>
<p class="text-sm text-base-content/60">Each language shows its own saved values; missing translations are left blank instead of using fallback text.</p>
</div>
<span class="badge badge-outline"><?= count($activeLanguages) ?> languages</span>
</div>
@@ -112,13 +112,41 @@ $javascriptValue = static function (string $value): string {
<?php
$firstLang = true;
foreach ($activeLanguages as $languageCode => $languageTranslation):
$savedTranslation = $pageTranslations[$languageCode] ?? null;
$hasSavedTranslation = is_array($savedTranslation);
$translationType = $fieldValue('type') !== '' ? $fieldValue('type') : ($page?->get('type') ?? 'static');
$hasRequiredTranslationValues = $hasSavedTranslation
&& trim((string) ($savedTranslation['route'] ?? '')) !== ''
&& ($translationType === 'redirect'
? trim((string) ($savedTranslation['target'] ?? '')) !== ''
: trim((string) ($savedTranslation['title'] ?? '')) !== '');
$localeStatus = $action === 'create'
? 'New translation'
: (! $hasSavedTranslation ? 'Missing' : ($hasRequiredTranslationValues ? 'Complete' : 'Needs attention'));
$localeStatusClass = $action === 'create'
? 'badge-outline'
: (! $hasSavedTranslation ? 'badge-error' : ($hasRequiredTranslationValues ? 'badge-success' : 'badge-warning'));
?>
<details class="collapse collapse-arrow border border-base-300 bg-base-100" <?= phpb_e($firstLang ? 'open' : '') ?>>
<summary class="collapse-title flex min-h-14 items-center text-base font-semibold sm:text-lg">
<summary class="collapse-title flex min-h-14 flex-wrap items-center gap-2 text-base font-semibold sm:text-lg">
<span><?= phpb_trans('languages.' . $languageCode) ?></span>
<span class="badge badge-ghost ml-3"><?= phpb_e($languageCode) ?></span>
<span class="badge badge-sm <?= $localeStatusClass ?>"><?= $localeStatus ?></span>
</summary>
<div class="collapse-content space-y-5">
<?php if ($action === 'create' || ! $hasSavedTranslation || ! $hasRequiredTranslationValues): ?>
<div class="alert <?= $hasSavedTranslation ? 'alert-warning' : 'alert-info' ?>" role="status">
<span>
<?php if ($action === 'create'): ?>
Enter the actual values for this language; other locales will not be used to fill these fields.
<?php elseif (! $hasSavedTranslation): ?>
No saved translation exists for this language. Enter its actual values; fields are not filled from another locale.
<?php else: ?>
This saved translation is missing a required title, route, or redirect target. Complete these fields before saving.
<?php endif; ?>
</span>
</div>
<?php endif; ?>
<div class="space-y-3" x-data="{route: <?= $javascriptValue($fieldValue('route', $languageCode)) ?>, empty: true, locale: <?= $javascriptValue($firstLang ? '' : '/' . $languageCode) ?>}" x-init="empty = route.length === 0">
<div class="form-control w-full">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-title">
@@ -148,7 +176,7 @@ $javascriptValue = static function (string $value): string {
<label class="label" for="<?= phpb_e($languageCode) ?>-page-target-redirect">
<span class="label-text"><?= phpb_trans('website-manager.target-redirect') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-target-redirect" name="target[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('target', $languageCode)) ?>" />
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-target-redirect" name="target[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($fieldValue('target', $languageCode)) ?>" :required="type==='redirect'" />
</div>
<div class="form-control w-full">
@@ -10,19 +10,20 @@
</a>
</header>
<div class="overflow-x-auto rounded-box border border-base-300 bg-base-100">
<table class="table table-zebra w-full min-w-[48rem]">
<table class="table table-zebra w-full min-w-[64rem]">
<thead>
<tr>
<th class="w-16">ID</th>
<th><?= phpb_trans('website-manager.name') ?></th>
<th><?= phpb_trans('website-manager.route') ?></th>
<th>Localized titles and routes</th>
<th>Coverage</th>
<th class="w-44"><?= phpb_trans('website-manager.actions') ?></th>
</tr>
</thead>
<tbody>
<?php if (empty($pages)): ?>
<tr>
<td colspan="4" class="py-12 text-center">
<td colspan="5" class="py-12 text-center">
<span class="mx-auto mb-3 grid size-11 place-items-center rounded-2xl bg-info/10 text-info">
<i class="text-2xl ph-duotone ph-files" aria-hidden="true"></i>
</span>
@@ -32,18 +33,60 @@
</tr>
<?php endif; ?>
<?php foreach ($pages as $page): ?>
<?php
$pageRoute = $page->getRoute();
$canViewPage = $page->get('type') !== 'redirect' && is_string($pageRoute) && $pageRoute !== '';
?>
<tr>
<td><?= phpb_e($page->getId()) ?></td>
<td class="font-medium"><?= phpb_e($page->getName()) ?></td>
<td>
<div class="hidden pl-4 pl-8"></div>
<div class="pl-<?= phpb_e((count(explode('/', $page->getRoute()))-2)*4) ?>">
<?= phpb_e($page->getRoute()) ?>
<div class="grid gap-2 sm:grid-cols-2">
<?php foreach ($activeLanguages as $languageCode => $languageTranslation): ?>
<?php
$localeCoverage = $pageTranslationCoverage[$page->getId()]['locales'][$languageCode] ?? null;
$localeExists = $localeCoverage['exists'] ?? false;
$localeComplete = $localeCoverage['complete'] ?? false;
$localeStatus = $localeComplete ? 'Complete' : ($localeExists ? 'Needs attention' : 'Missing');
$localeBadgeClass = $localeComplete ? 'badge-success' : ($localeExists ? 'badge-warning' : 'badge-error');
$localeTitle = $localeCoverage['title'] ?? null;
$localeRoute = $localeCoverage['route'] ?? null;
$localeTitleLabel = is_string($localeTitle) && trim($localeTitle) !== ''
? phpb_e($localeTitle)
: ($page->get('type') === 'redirect' ? 'Redirect page' : 'Title not set');
?>
<div class="min-w-0 rounded-box border border-base-300 p-3">
<div class="mb-1 flex flex-wrap items-center justify-between gap-2">
<span class="text-xs font-semibold text-base-content/70">
<?= phpb_trans('languages.' . $languageCode) ?>
<span class="font-mono">(<?= phpb_e($languageCode) ?>)</span>
</span>
<span class="badge badge-sm <?= $localeBadgeClass ?>"><?= $localeStatus ?></span>
</div>
<p class="truncate text-sm font-medium" title="<?= phpb_e($localeTitle) ?>">
<?= $localeTitleLabel ?>
</p>
<p class="break-all font-mono text-xs text-base-content/60" title="<?= phpb_e($localeRoute) ?>">
<?= is_string($localeRoute) && trim($localeRoute) !== '' ? phpb_e($localeRoute) : 'Route not set' ?>
</p>
</div>
<?php endforeach; ?>
</div>
</td>
<td>
<?php
$pageCoverage = $pageTranslationCoverage[$page->getId()] ?? ['completeCount' => 0, 'localeCount' => count($activeLanguages)];
$coverageClass = $pageCoverage['localeCount'] > 0 && $pageCoverage['completeCount'] === $pageCoverage['localeCount']
? 'badge-success'
: ($pageCoverage['completeCount'] > 0 ? 'badge-warning' : 'badge-error');
?>
<span class="badge <?= $coverageClass ?>">
<?= phpb_e($pageCoverage['completeCount']) ?> / <?= phpb_e($pageCoverage['localeCount']) ?> complete
</span>
</td>
<td>
<div class="flex items-center gap-1">
<a href="<?= phpb_e(phpb_full_url($page->getRoute())) ?>" title="<?= phpb_trans('website-manager.view') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.view')) ?>" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-square btn-sm <?= $page->get('type') === 'redirect' ? 'btn-disabled' : '' ?>" <?= $page->get('type') === 'redirect' ? 'tabindex="-1" aria-disabled="true"' : '' ?>>
<a href="<?= phpb_e($canViewPage ? phpb_full_url($pageRoute) : '#') ?>" title="<?= phpb_trans('website-manager.view') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.view')) ?>" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-square btn-sm <?= $canViewPage ? '' : 'btn-disabled' ?>" <?= $canViewPage ? '' : 'tabindex="-1" aria-disabled="true"' ?>>
<i class="text-xl ph-duotone ph-eye" aria-hidden="true"></i>
</a>
<a href="<?= phpb_url('pagebuilder', ['page' => $page->getId()]) ?>" class="btn btn-primary btn-square btn-sm <?= $page->get('type') === 'redirect' ? 'btn-disabled' : '' ?>" title="<?= phpb_trans('website-manager.edit') ?>" aria-label="<?= phpb_e(phpb_trans('website-manager.edit')) ?>" <?= $page->get('type') === 'redirect' ? 'tabindex="-1" aria-disabled="true"' : '' ?>>
+5 -13
View File
@@ -129,14 +129,7 @@ class Page implements PageContract
public function getTranslation(string $setting, ?string $locale = null)
{
$translations = $this->getTranslations();
if (empty($translations)) {
return null;
}
$locale = $locale ?? phpb_config('general.language');
return $translations[$locale][$setting] ??
$translations['en'][$setting] ??
$translations[array_keys($translations)[0]][$setting] ??
null;
return (new PageTranslationService())->resolveTranslation($translations, $setting, $locale);
}
/**
@@ -178,11 +171,10 @@ class Page implements PageContract
*/
public function invalidateCache()
{
$cache = phpb_instance('cache');
$routes = array_map(function ($translation) {
return $translation['route'] ?? null;
}, $this->getTranslations());
foreach ($this->getTranslations() as $locale => $translationData) {
$languageRoute = $this->getRoute($locale);
$cache->invalidate($languageRoute);
}
(new PageTranslationService())->invalidateRoutes($routes);
}
}
+206
View File
@@ -0,0 +1,206 @@
<?php
namespace Plugi;
use Plugi\Repositories\PageTranslationRepository;
class PageTranslationService
{
/**
* Return the requested locale, configured default, or first available locale, in that order.
*
* @param string|null $locale
* @param array $availableLocales
* @return string[]
*/
public function getLocaleFallbackOrder(?string $locale, array $availableLocales): array
{
$availableLocales = $this->getAvailableLocales($availableLocales);
$fallbackLocales = [];
foreach ([$locale, phpb_config('general.language')] as $preferredLocale) {
if (is_string($preferredLocale) && in_array($preferredLocale, $availableLocales, true)) {
$fallbackLocales[] = $preferredLocale;
}
}
foreach ($availableLocales as $availableLocale) {
$fallbackLocales[] = $availableLocale;
}
return array_values(array_unique($fallbackLocales));
}
/**
* Resolve a locale using the shared fallback order.
*
* @param string|null $locale
* @param array $availableLocales
* @return string|null
*/
public function resolveLocale(?string $locale, array $availableLocales): ?string
{
return $this->getLocaleFallbackOrder($locale, $availableLocales)[0] ?? null;
}
/**
* Determine whether a locale is active without applying fallback.
*
* @param string|null $locale
* @param array $availableLocales
* @return bool
*/
public function isAvailableLocale(?string $locale, array $availableLocales): bool
{
return $locale !== null && in_array($locale, $this->getAvailableLocales($availableLocales), true);
}
/**
* Return the setting from the first translation containing a non-null value.
*
* @param array $translations
* @param string $setting
* @param string|null $locale
* @return mixed|null
*/
public function resolveTranslation(array $translations, string $setting, ?string $locale = null)
{
foreach ($this->getLocaleFallbackOrder($locale, array_keys($translations)) as $fallbackLocale) {
if (array_key_exists($setting, $translations[$fallbackLocale]) && $translations[$fallbackLocale][$setting] !== null) {
return $translations[$fallbackLocale][$setting];
}
}
return null;
}
/**
* Return every stored route for a page, including inactive locales.
*
* @param mixed $pageId
* @return string[]
*/
public function getPageRoutes($pageId): array
{
$translations = (new PageTranslationRepository())->getForPages([$pageId]);
$routes = [];
foreach ($translations as $translation) {
$route = $translation->route ?? null;
if (is_string($route) && $route !== '') {
$routes[] = $route;
}
}
$routes = array_values(array_unique($routes));
sort($routes, SORT_STRING);
return $routes;
}
/**
* Invalidate routes after their corresponding persistence operation succeeds.
*
* @param array $routes
*/
public function invalidateRoutes(array $routes): void
{
$routes = array_values(array_unique(array_filter($routes, function ($route) {
return is_string($route) && $route !== '';
})));
sort($routes, SORT_STRING);
if (empty($routes)) {
return;
}
$cache = phpb_instance('cache');
if (! $cache) {
return;
}
foreach ($routes as $route) {
$cache->invalidate($route);
}
}
/**
* Return actual saved translation coverage for the given pages and active locales.
*
* @param array $pages
* @param array $activeLanguages
* @return array
*/
public function getPageCoverage(array $pages, array $activeLanguages): array
{
$coverage = [];
$pageTypes = [];
$pageIds = [];
foreach ($pages as $page) {
$pageId = (string) $page->getId();
$pageIds[] = $page->getId();
$pageTypes[$pageId] = $page->get('type');
$coverage[$pageId] = [
'completeCount' => 0,
'localeCount' => count($activeLanguages),
'locales' => [],
];
foreach ($activeLanguages as $locale => $language) {
$coverage[$pageId]['locales'][$locale] = [
'exists' => false,
'complete' => false,
'title' => null,
'route' => null,
];
}
}
if (empty($pageIds)) {
return $coverage;
}
$foreignKey = phpb_config('page.translation.foreign_key');
$translations = (new PageTranslationRepository())->getForPages($pageIds);
foreach ($translations as $translation) {
$pageId = (string) ($translation->$foreignKey ?? '');
$locale = $translation->locale ?? null;
if (! isset($coverage[$pageId]) || ! is_string($locale) || ! array_key_exists($locale, $activeLanguages)) {
continue;
}
$title = $translation->title ?? null;
$route = $translation->route ?? null;
$target = $translation->target ?? null;
$hasRequiredValue = $pageTypes[$pageId] === 'redirect'
? trim((string) $target) !== ''
: trim((string) $title) !== '';
$isComplete = trim((string) $route) !== '' && $hasRequiredValue;
$coverage[$pageId]['locales'][$locale] = [
'exists' => true,
'complete' => $isComplete,
'title' => $title,
'route' => $route,
];
if ($isComplete) {
$coverage[$pageId]['completeCount']++;
}
}
return $coverage;
}
/**
* Normalize a list or locale-keyed language map to locale codes.
*
* @param array $availableLocales
* @return string[]
*/
private function getAvailableLocales(array $availableLocales): array
{
if ($availableLocales === [] || array_keys($availableLocales) !== range(0, count($availableLocales) - 1)) {
$availableLocales = array_keys($availableLocales);
}
return array_values(array_filter($availableLocales, function ($availableLocale) {
return is_string($availableLocale) && $availableLocale !== '';
}));
}
}
+25 -9
View File
@@ -5,6 +5,7 @@ namespace Plugi\Repositories;
use Plugi\Contracts\PageContract;
use Plugi\Contracts\PageRepositoryContract;
use Plugi\Contracts\PageTranslationContract;
use Plugi\PageTranslationService;
class PageRepository extends BaseRepository implements PageRepositoryContract
{
@@ -90,7 +91,10 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
return false;
}
$updateResult = $this->db->transaction(function () use ($page, $data) {
$translationService = new PageTranslationService();
$oldRoutes = [];
$updateResult = $this->db->transaction(function () use ($page, $data, $translationService, &$oldRoutes) {
$oldRoutes = $translationService->getPageRoutes($page->getId());
if (! $this->replaceTranslations($page, $data)) {
return false;
}
@@ -102,7 +106,7 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
]);
});
if ($updateResult) {
$page->invalidateCache();
$translationService->invalidateRoutes(array_merge($oldRoutes, array_values($data['route'])));
}
return $updateResult;
}
@@ -185,13 +189,9 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
$routes[$route] = true;
}
$foreignKey = phpb_config('page.translation.foreign_key');
$pageTranslationRepository = new PageTranslationRepository;
foreach ($pageTranslationRepository->getAll(['route', $foreignKey]) as $translation) {
if ($pageId !== null && (string) $translation->$foreignKey === (string) $pageId) {
continue;
}
if (array_key_exists($translation->route, $routes)) {
foreach (array_keys($routes) as $route) {
if ($pageTranslationRepository->routeExists($route, $pageId)) {
return true;
}
}
@@ -211,7 +211,9 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
$updateResult = parent::update($page, [
'data' => json_encode($data),
]);
if ($updateResult) {
$page->invalidateCache();
}
return $updateResult;
}
@@ -223,8 +225,22 @@ class PageRepository extends BaseRepository implements PageRepositoryContract
*/
public function destroy($id)
{
$this->findWithId($id)->invalidateCache();
$translationService = new PageTranslationService();
$routes = [];
$destroyResult = $this->db->transaction(function () use ($id, $translationService, &$routes) {
$routes = $translationService->getPageRoutes($id);
$pageTranslationRepository = new PageTranslationRepository();
if (! $pageTranslationRepository->destroyWhere(phpb_config('page.translation.foreign_key'), $id)) {
return false;
}
return parent::destroy($id);
});
if ($destroyResult) {
$translationService->invalidateRoutes($routes);
}
return $destroyResult;
}
}
@@ -29,4 +29,47 @@ class PageTranslationRepository extends BaseRepository implements PageTranslatio
parent::__construct();
$this->class = phpb_instance('page.translation');
}
/**
* Determine whether a route is already used by another page translation.
*
* @param string $route
* @param mixed|null $excludedPageId
* @return bool
*/
public function routeExists(string $route, $excludedPageId = null): bool
{
$query = "SELECT 1 FROM {$this->table} WHERE route = ?";
$parameters = [$route];
if ($excludedPageId !== null) {
$foreignKey = $this->removeNonAlphaNumeric(phpb_config('page.translation.foreign_key'));
$query .= " AND {$foreignKey} != ?";
$parameters[] = $excludedPageId;
}
$query .= ' LIMIT 1';
return ! empty($this->db->select($query, $parameters));
}
/**
* Return translations belonging to the given page IDs.
*
* @param array $pageIds
* @return array
*/
public function getForPages(array $pageIds): array
{
if (empty($pageIds)) {
return [];
}
$foreignKey = $this->removeNonAlphaNumeric(phpb_config('page.translation.foreign_key'));
$placeholders = implode(', ', array_fill(0, count($pageIds), '?'));
$records = $this->db->select(
"SELECT * FROM {$this->table} WHERE {$foreignKey} IN ({$placeholders})",
array_values($pageIds)
);
return $this->createInstances($records);
}
}
@@ -0,0 +1,110 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const sourcePath = new URL('../src/Modules/GrapesJS/resources/assets/js/save-page.js', import.meta.url);
const source = fs.readFileSync(sourcePath, 'utf8');
class TestElement {
constructor() {
this._innerHTML = '';
}
set innerHTML(value) {
this._innerHTML = value;
}
get innerHTML() {
return this._innerHTML;
}
querySelectorAll() {
const pattern = /<div([^>]*\bphpb-blocks-container\b[^>]*)>([\s\S]*?)<\/div>/g;
return [...this._innerHTML.matchAll(pattern)].map((match, index) => {
return new TestContainer(this, index, `<div${match[1]}>`, match[2]);
});
}
replaceContainer(index, containerHtml) {
const pattern = /<div([^>]*\bphpb-blocks-container\b[^>]*)>([\s\S]*?)<\/div>/g;
let currentIndex = 0;
this._innerHTML = this._innerHTML.replace(pattern, match => {
return currentIndex++ === index ? containerHtml : match;
});
}
appendChild(container) {
this._innerHTML += container.outerHTML;
}
}
class TestContainer {
constructor(parent, index, openingTag, innerHTML) {
this.parent = parent;
this.index = index;
this.openingTag = openingTag;
this._innerHTML = innerHTML;
}
set innerHTML(value) {
this._innerHTML = value;
this.parent.replaceContainer(this.index, `${this.openingTag}${value}</div>`);
}
get innerHTML() {
return this._innerHTML;
}
get outerHTML() {
return `${this.openingTag}${this._innerHTML}</div>`;
}
cloneNode() {
return new TestContainer(null, 0, this.openingTag, this._innerHTML);
}
}
const window = {};
const document = {
getElementById: () => null,
addEventListener: () => {},
createElement: () => new TestElement(),
};
vm.runInNewContext(source, { window, document, console, setTimeout, URLSearchParams });
const sourceBlocks = {
parent: {
html: '<p>Source locale text</p><div phpb-blocks-container>[block slug="child" id="new-child"]</div>',
settings: {label: 'Source setting'},
blocks: {
existingChild: {html: '<p>Source child text</p>', settings: {label: 'Source child setting'}},
newChild: {html: '<p>New shared block</p>', settings: {label: 'New setting'}},
},
},
newParent: {html: '<p>New shared parent</p>', settings: {label: 'New parent setting'}},
};
const targetBlocks = {
parent: {
html: '<p>Translated parent text</p><div phpb-blocks-container>[block slug="child" id="existing-child"]</div>',
settings: {label: 'Translated parent setting'},
blocks: {
existingChild: {html: '<p>Existing translated child</p>', settings: {label: 'Translated child setting'}},
},
},
localeOnlyParent: {html: '<p>Existing locale-only content</p>'},
};
const synchronizedBlocks = window.synchronizePageBlockVariants(sourceBlocks, targetBlocks);
assert.match(synchronizedBlocks.parent.html, /Translated parent text/);
assert.match(synchronizedBlocks.parent.html, /id="new-child"/);
assert.equal(synchronizedBlocks.parent.settings.label, 'Translated parent setting');
assert.equal(synchronizedBlocks.parent.blocks.existingChild.html, '<p>Existing translated child</p>');
assert.equal(synchronizedBlocks.parent.blocks.existingChild.settings.label, 'Translated child setting');
assert.equal(synchronizedBlocks.parent.blocks.newChild.html, '<p>New shared block</p>');
assert.equal(synchronizedBlocks.newParent.html, '<p>New shared parent</p>');
assert.equal(synchronizedBlocks.localeOnlyParent.html, '<p>Existing locale-only content</p>');
sourceBlocks.parent.blocks.newChild.html = '<p>Source changed after synchronization</p>';
assert.equal(synchronizedBlocks.parent.blocks.newChild.html, '<p>New shared block</p>');
console.log('PASS: shared block structure synchronizes without overwriting existing locale content.');
@@ -21,6 +21,7 @@ require_once __DIR__ . '/../src/Contracts/ThemeContract.php';
require_once __DIR__ . '/../src/Core/DB.php';
require_once __DIR__ . '/../src/Repositories/BaseRepository.php';
require_once __DIR__ . '/../src/Repositories/PageTranslationRepository.php';
require_once __DIR__ . '/../src/PageTranslationService.php';
require_once __DIR__ . '/../src/Page.php';
require_once __DIR__ . '/../src/PageTranslation.php';
require_once __DIR__ . '/../src/Repositories/PageRepository.php';
@@ -31,8 +32,13 @@ require_once __DIR__ . '/../src/Modules/GrapesJS/PageBuilder.php';
class PageCreationTestDatabase extends DB
{
public int $translationInsertCount = 0;
public int $pageTranslationAllCallCount = 0;
public int $pageTranslationBatchSelectCount = 0;
public ?int $failOnTranslationInsert = null;
public bool $throwOnTranslationFailure = false;
public ?string $failOnDeleteTable = null;
public bool $throwOnDeleteFailure = false;
public bool $failOnPageUpdate = false;
public function __construct()
{
@@ -43,6 +49,16 @@ class PageCreationTestDatabase extends DB
public function query(string $query, array $parameters = [])
{
if ($this->failOnDeleteTable !== null && str_starts_with($query, 'DELETE FROM ' . $this->failOnDeleteTable)) {
if ($this->throwOnDeleteFailure) {
throw new PDOException('Simulated page deletion failure.');
}
return false;
}
if ($this->failOnPageUpdate && str_starts_with($query, 'UPDATE pages SET')) {
return false;
}
if (str_starts_with($query, 'INSERT INTO page_translations')) {
$this->translationInsertCount++;
if ($this->translationInsertCount === $this->failOnTranslationInsert) {
@@ -56,6 +72,24 @@ class PageCreationTestDatabase extends DB
return parent::query($query, $parameters);
}
public function all(string $table, array|string $columns = '*'): array
{
if ($table === 'page_translations') {
$this->pageTranslationAllCallCount++;
}
return parent::all($table, $columns);
}
public function select(string $query, array $parameters): array
{
if (str_starts_with($query, 'SELECT * FROM page_translations WHERE page_id IN (')) {
$this->pageTranslationBatchSelectCount++;
}
return parent::select($query, $parameters);
}
public function createSchema(): void
{
$this->pdo->exec('CREATE TABLE pages (
@@ -102,8 +136,11 @@ class PageCreationTestWebsiteManager extends WebsiteManager
class PageCreationTestCache
{
public static array $invalidatedRoutes = [];
public function invalidate(string $route): void
{
self::$invalidatedRoutes[] = $route;
}
}
@@ -165,6 +202,11 @@ function phpb_url(string $module, array $parameters = []): string
return '/' . $module;
}
function phpb_full_url(string $route): string
{
return 'https://example.test' . $route;
}
function phpb_csrf_field(): void
{
}
@@ -175,6 +217,9 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
$_ENV['DATABASE_PREFIX'] = '';
$pageCreationConfig = [
'general' => [
'language' => 'en',
],
'page' => [
'table' => 'pages',
'translation' => [
@@ -184,6 +229,7 @@ function resetPageCreationDatabase(array $languages = ['en' => [], 'de' => []]):
],
];
$pageCreationLanguages = $languages;
PageCreationTestCache::$invalidatedRoutes = [];
$phpb_db = new PageCreationTestDatabase();
$phpb_db->createSchema();
}
@@ -222,6 +268,21 @@ function runPageCreationCase(string $name, callable $case): bool
}
$cases = [
'configured locale is preferred over the first available translation' => function (): void {
resetPageCreationDatabase(['de' => [], 'fr' => []]);
global $pageCreationConfig;
$pageCreationConfig['general']['language'] = 'fr';
$page = new Page();
$page->setTranslations([
'de' => ['title' => 'Deutscher Titel'],
'fr' => ['title' => 'Titre français'],
]);
assertPageCreation(
$page->getTranslation('title', 'it') === 'Titre français',
'Missing requested locale should fall back to the configured default, not the first saved locale.'
);
},
'locked generated routes do not leave a base page without translations' => function (): void {
resetPageCreationDatabase();
$payload = pageCreationPayload();
@@ -321,6 +382,54 @@ $cases = [
assertPageCreation(str_contains($malformedHtml, '\\u0027\\u003C/script\\u003E'), 'Submitted route was not safely encoded for Alpine.');
$_POST = [];
},
'page settings leave missing locale values blank and explain the missing translation' => function (): void {
resetPageCreationDatabase();
$page = new Page();
$page->setData([
'id' => 42,
'name' => 'English page',
'layout' => 'default',
'type' => 'static',
]);
$page->setTranslations([
'en' => [
'title' => 'English title',
'route' => '/english-page',
'meta_title' => '',
'meta_description' => '',
'target' => '',
],
]);
$_POST = [];
$action = 'edit';
$errorMessage = null;
$theme = new class {
public function getThemeLayouts(): array
{
return [new class {
public function getSlug(): string
{
return 'default';
}
public function getTitle(): string
{
return 'Default';
}
}];
}
};
ob_start();
include __DIR__ . '/../src/Modules/WebsiteManager/resources/views/page-settings.php';
$html = ob_get_clean();
preg_match('/name="title\[de\]" value="([^"]*)"/', $html, $germanTitle);
assertPageCreation(($germanTitle[1] ?? null) === '', 'Missing German title was filled from the English translation.');
assertPageCreation(str_contains($html, 'No saved translation exists for this language.'), 'The missing locale was not explained.');
assertPageCreation(str_contains($html, 'Each language shows its own saved values; missing translations are left blank instead of using fallback text.'), 'Locale-specific editing guidance was not shown.');
$_POST = [];
},
'generated routes persist for every active locale' => function (): void {
resetPageCreationDatabase();
@@ -403,6 +512,156 @@ $cases = [
assertPageCreation($secondPage === false, 'Duplicate route was not rejected.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Duplicate create left an extra base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Duplicate create changed translations.');
assertPageCreation($phpb_db->pageTranslationAllCallCount === 0, 'Route validation loaded every translation instead of querying for a collision.');
},
'route collision checks allow an unchanged page route and reject another locale collision' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
assertPageCreation($repository->update($page, pageCreationPayload()) === true, 'An unchanged route should not collide with its own page.');
assertPageCreation(
$repository->create(pageCreationPayload([
'name' => 'German route collision',
'route' => ['en' => '/unique-route', 'de' => '/de/new-page'],
])) === false,
'A route collision in a non-default locale was not rejected.'
);
assertPageCreation($phpb_db->pageTranslationAllCallCount === 0, 'Route validation loaded every translation instead of querying for a collision.');
},
'page locale coverage summarizes complete partial and absent translations in one batch' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload([
'route' => ['en' => '/complete-en', 'de' => '/complete-de'],
]));
$repository->create(pageCreationPayload([
'name' => 'Partial page',
'route' => ['en' => '/partial-en', 'de' => '/partial-de'],
]));
$repository->create(pageCreationPayload([
'name' => 'Missing locale page',
'route' => ['en' => '/missing-en', 'de' => '/missing-de'],
]));
$pages = $repository->getAll();
$pageRows = [];
foreach ($pages as $page) {
$pageRows[$page->getId()] = $page;
}
global $phpb_db;
$pageIds = array_keys($pageRows);
$phpb_db->query('UPDATE page_translations SET title = ? WHERE page_id = ? AND locale = ?', ['', $pageIds[1], 'de']);
$phpb_db->query('DELETE FROM page_translations WHERE page_id = ? AND locale = ?', [$pageIds[2], 'de']);
$missingPage = new Page();
$missingPage->setData(['id' => 999, 'type' => 'static']);
$pages[] = $missingPage;
$phpb_db->pageTranslationBatchSelectCount = 0;
$coverage = (new Plugi\PageTranslationService())->getPageCoverage($pages, phpb_active_languages());
assertPageCreation($coverage[$pageIds[0]]['completeCount'] === 2, 'A complete page did not report all active locales complete.');
assertPageCreation($coverage[$pageIds[1]]['completeCount'] === 1, 'A partially complete page reported the wrong coverage count.');
assertPageCreation($coverage[$pageIds[1]]['locales']['de']['exists'] === true, 'An incomplete saved locale was reported as missing.');
assertPageCreation($coverage[$pageIds[1]]['locales']['de']['complete'] === false, 'An incomplete saved locale was reported as complete.');
assertPageCreation($coverage[$pageIds[2]]['locales']['de']['exists'] === false, 'An absent locale was reported as saved.');
assertPageCreation($coverage[999]['completeCount'] === 0, 'A page without translation records reported complete locales.');
assertPageCreation($phpb_db->pageTranslationBatchSelectCount === 1, 'Translation coverage used more than one batched repository query.');
$activeLanguages = phpb_active_languages();
$pageTranslationCoverage = $coverage;
ob_start();
include __DIR__ . '/../src/Modules/WebsiteManager/resources/views/tabs/pages.php';
$html = ob_get_clean();
assertPageCreation(str_contains($html, '/complete-en'), 'The page overview did not render the saved English route.');
assertPageCreation(str_contains($html, '/complete-de'), 'The page overview did not render the saved German route.');
assertPageCreation(str_contains($html, 'New page'), 'The page overview did not render a saved localized title.');
assertPageCreation(str_contains($html, '2 / 2 complete'), 'The page overview did not render the translation coverage summary.');
},
'successful route updates invalidate old and new localized routes' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$result = $repository->update($page, pageCreationPayload([
'route' => ['en' => '/changed-en', 'de' => '/changed-de'],
]));
assertPageCreation($result === true, 'A valid route update failed.');
assertPageCreation(
PageCreationTestCache::$invalidatedRoutes === ['/changed-de', '/changed-en', '/de/new-page', '/new-page'],
'A successful route update did not invalidate both old and new localized route caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'page deletion removes translations and invalidates routes after commit' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload([
'route' => ['en' => '/delete-en', 'de' => '/delete-de'],
]));
global $phpb_db;
$pageId = $phpb_db->rows('pages')[0]['id'];
assertPageCreation($repository->destroy($pageId) === true, 'Page deletion failed.');
assertPageCreation(count($phpb_db->rows('pages')) === 0, 'Page deletion left the base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 0, 'Page deletion left translation rows.');
assertPageCreation(
PageCreationTestCache::$invalidatedRoutes === ['/delete-de', '/delete-en'],
'Successful deletion did not invalidate every stored localized route: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'failed page deletion rolls back translation cleanup without invalidating caches' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$pageId = $phpb_db->rows('pages')[0]['id'];
$phpb_db->failOnDeleteTable = 'pages';
assertPageCreation($repository->destroy($pageId) === false, 'A failed base-row deletion was reported as successful.');
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Failed deletion removed the base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Failed deletion did not roll back translation cleanup.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Failed deletion invalidated route caches.');
},
'exception during page deletion rolls back rows and leaves caches intact' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$pageId = $phpb_db->rows('pages')[0]['id'];
$phpb_db->failOnDeleteTable = 'pages';
$phpb_db->throwOnDeleteFailure = true;
try {
$repository->destroy($pageId);
} catch (PDOException) {
}
assertPageCreation(count($phpb_db->rows('pages')) === 1, 'Deletion exception removed the base page.');
assertPageCreation(count($phpb_db->rows('page_translations')) === 2, 'Deletion exception did not roll back translation cleanup.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Deletion exception invalidated route caches.');
},
'page content cache invalidation occurs only after successful writes' => function (): void {
resetPageCreationDatabase();
$repository = new PageRepository();
$repository->create(pageCreationPayload());
global $phpb_db;
$page = $repository->findWithId($phpb_db->rows('pages')[0]['id']);
$phpb_db->failOnPageUpdate = true;
assertPageCreation($repository->updatePageData($page, ['html' => []]) === false, 'A failed page-data update was reported as successful.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'A failed page-data update invalidated route caches.');
$phpb_db->failOnPageUpdate = false;
assertPageCreation($repository->updatePageData($page, ['html' => []]) === true, 'A valid page-data update failed.');
assertPageCreation(
PageCreationTestCache::$invalidatedRoutes === ['/de/new-page', '/new-page'],
'A successful page-data update did not invalidate localized route caches: ' . json_encode(PageCreationTestCache::$invalidatedRoutes)
);
},
'translation write failures roll back the base page and translations' => function (): void {
resetPageCreationDatabase();
@@ -449,6 +708,7 @@ $cases = [
assertPageCreation(count($translations) === 2, 'Failed update changed the translation count.');
assertPageCreation($translations[0]['route'] === '/new-page', 'Failed update did not restore the English route.');
assertPageCreation($translations[1]['route'] === '/de/new-page', 'Failed update did not restore the German route.');
assertPageCreation(PageCreationTestCache::$invalidatedRoutes === [], 'Failed metadata update invalidated route caches.');
},
];
@@ -0,0 +1,111 @@
<?php
require_once __DIR__ . '/../src/PageTranslationService.php';
$pageTranslationServiceConfig = [
'general' => [
'language' => 'en',
],
];
function phpb_config(?string $key = null): mixed
{
global $pageTranslationServiceConfig;
if ($key === null) {
return $pageTranslationServiceConfig;
}
$value = $pageTranslationServiceConfig;
foreach (explode('.', $key) as $segment) {
if (! is_array($value) || ! array_key_exists($segment, $value)) {
return '';
}
$value = $value[$segment];
}
return $value;
}
function assertPageTranslationService(bool $condition, string $message): void
{
if (! $condition) {
throw new RuntimeException($message);
}
}
function runPageTranslationServiceCase(string $name, callable $case): bool
{
try {
$case();
fwrite(STDOUT, "PASS: {$name}\n");
return true;
} catch (Throwable $exception) {
fwrite(STDERR, "FAIL: {$name}: {$exception->getMessage()}\n");
return false;
}
}
$service = new Plugi\PageTranslationService();
$cases = [
'requested locale wins when available' => function () use ($service): void {
assertPageTranslationService(
$service->resolveLocale('fr', ['de', 'fr']) === 'fr',
'An available requested locale should be selected before the configured default.'
);
},
'configured locale wins when requested locale is absent' => function () use ($service): void {
global $pageTranslationServiceConfig;
$pageTranslationServiceConfig['general']['language'] = 'fr';
assertPageTranslationService(
$service->resolveLocale('it', ['de', 'fr']) === 'fr',
'The configured default should be used when the requested locale is unavailable.'
);
},
'first available locale is used when configured locale is unavailable' => function () use ($service): void {
global $pageTranslationServiceConfig;
$pageTranslationServiceConfig['general']['language'] = 'en';
assertPageTranslationService(
$service->resolveLocale('it', ['de', 'fr']) === 'de',
'The first available locale should be used without assuming an English translation exists.'
);
},
'no available locale resolves to null' => function () use ($service): void {
assertPageTranslationService($service->resolveLocale('en', []) === null, 'An empty locale list should resolve to null.');
},
'unsupported locales are rejected instead of receiving fallback' => function () use ($service): void {
assertPageTranslationService(
$service->isAvailableLocale('en', ['en' => 'English'])
&& ! $service->isAvailableLocale('it', ['en' => 'English']),
'Locale validation should accept active languages only and must not apply fallback.'
);
},
'translation values follow the same fallback order and preserve empty strings' => function () use ($service): void {
global $pageTranslationServiceConfig;
$pageTranslationServiceConfig['general']['language'] = 'fr';
$translations = [
'de' => ['title' => 'Deutscher Titel', 'meta_title' => ''],
'fr' => ['title' => 'Titre français', 'meta_title' => 'Titre de métadonnées'],
];
assertPageTranslationService(
$service->resolveTranslation($translations, 'title', 'it') === 'Titre français',
'Translation metadata did not use the configured locale fallback.'
);
assertPageTranslationService(
$service->resolveTranslation($translations, 'meta_title', 'de') === '',
'An intentionally empty translation should not be replaced by fallback text.'
);
},
];
$passed = 0;
foreach ($cases as $name => $case) {
if (runPageTranslationServiceCase($name, $case)) {
$passed++;
}
}
fwrite(STDOUT, sprintf("%d/%d page translation service cases passed.\n", $passed, count($cases)));
exit($passed === count($cases) ? 0 : 1);