Name nur zur Orientierung, Sprungmarke als Element-Kennung (je Seite eindeutig, reservierte Kennungen gesperrt), ausgeblendete Abschnitte erscheinen nie öffentlich und zählen weder für die Hauptüberschrift noch für Trenner. SafeUrl nimmt #marke an. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
466 lines
18 KiB
PHP
466 lines
18 KiB
PHP
<?php
|
|
|
|
namespace App\Domain\Cms\Sections;
|
|
|
|
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
|
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
|
use App\Domain\Cms\Widgets\WidgetErrors;
|
|
use App\Domain\Cms\Widgets\WidgetRegistry;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
/**
|
|
* Abschnitts- und Slotmodell einer Seite: Seite → Abschnitte → Slots → Widget-Instanzen.
|
|
*
|
|
* Gespeicherte Hülle eines Abschnitts (Version 1):
|
|
* {id, v, layout, style: {background, image, focus, overlay, width, spacing_top, spacing_bottom, gap, divider}, slots: [Widget-Hülle|null, …]}
|
|
*
|
|
* Version 2 (Abstände): oben, unten und Widget-Abstand sind drei unabhängige Werte. Hüllen der Version 1 werden beim
|
|
* Lesen übersetzt (SectionStyle::migrateSpacing), ohne die Darstellung zu ändern; gespeicherte Revisionen bleiben.
|
|
*
|
|
* Optionale Felder des Abschnitts (abwärtskompatibel, fehlen in älteren Revisionen):
|
|
* - name: interner Name zur Orientierung im Seitenaufbau (nie öffentlich), höchstens 80 Zeichen;
|
|
* - anchor: Sprungmarke, wird als Element-Kennung des Abschnitts ausgegeben (Link „#marke“ oder „/pfad#marke“),
|
|
* je Seite eindeutig, nur Kleinbuchstaben, Ziffern und Bindestriche;
|
|
* - hidden: true blendet den Abschnitt auf der Website aus; er bleibt im Entwurf und in den Revisionen erhalten.
|
|
* Ältere Programmstände kennen „hidden“ nicht und würden einen ausgeblendeten Abschnitt zeigen (siehe Release-Vorbereitung).
|
|
*
|
|
* Jeder Slot enthält höchstens ein Widget aus dem zentralen Widget-Register. Abschnitte sind nicht verschachtelbar.
|
|
* Revisionen ohne Abschnitte (Bestand vor dieser Fassung) werden beim Lesen als einspaltige Abschnitte gelesen.
|
|
*/
|
|
class PageSections
|
|
{
|
|
public const VERSION = 2;
|
|
|
|
public const MAX_SECTIONS = 30;
|
|
|
|
public const MAX_WIDGETS = 60;
|
|
|
|
public const MAX_NAME = 80;
|
|
|
|
public const MAX_ANCHOR = 60;
|
|
|
|
/**
|
|
* Kennungen, die im Seitengerüst schon vergeben sind (Hauptbereich, Navigation, Fuß) oder als Vorgabe dienen.
|
|
* Eine Sprungmarke darf sie nicht wiederholen.
|
|
*
|
|
* @var list<string>
|
|
*/
|
|
public const RESERVED_ANCHORS = ['inhalt', 'main', 'top', 'site-nav', 'fuss-themen', 'mb-account-menu'];
|
|
|
|
public const ANCHOR_PATTERN = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/';
|
|
|
|
public function __construct(private readonly WidgetRegistry $widgets) {}
|
|
|
|
/**
|
|
* Lesepfad. Unbekannte Werte fallen auf Vorgaben zurück, unbekannte Widget-Arten entfallen.
|
|
*
|
|
* @param array<int|string, mixed>|null $sections gespeicherte Abschnitte (Spalte sections)
|
|
* @param array<int|string, mixed>|null $blocks flache Bausteinliste (Spalte blocks), nur ohne Abschnitte verwendet
|
|
* @return list<array{id: ?string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
|
*/
|
|
public function read(?array $sections, ?array $blocks = null): array
|
|
{
|
|
if ($sections === null) {
|
|
return $this->wrapWidgets($blocks ?? []);
|
|
}
|
|
|
|
$result = [];
|
|
|
|
foreach (SectionStyle::migrateSpacing(array_values(array_filter($sections, 'is_array')), byVersion: true) as $section) {
|
|
$result[] = $this->upcastSection($section);
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* Schreibpfad: prüft und bereinigt Abschnitte für eine neue Revision. Flache Widgets (ohne „slots“) werden
|
|
* als einspaltige Abschnitte übernommen. Alle Fehler der Seite werden gesammelt gemeldet; Schlüssel:
|
|
* „sections.N.layout“, „sections.N.style.image“, „sections.N.slots“, „sections.N.slots.M.data.feld“.
|
|
*
|
|
* @param array<int|string, mixed> $content
|
|
* @return list<array{id: string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
|
*/
|
|
public function normalize(array $content): array
|
|
{
|
|
$items = array_values($content);
|
|
|
|
if (count($items) > self::MAX_SECTIONS) {
|
|
throw ValidationException::withMessages([
|
|
'sections' => 'Eine Seite hat höchstens '.self::MAX_SECTIONS.' Abschnitte.',
|
|
]);
|
|
}
|
|
|
|
$errors = [];
|
|
$sections = [];
|
|
$seenSectionIds = [];
|
|
$seenWidgetIds = [];
|
|
$seenAnchors = [];
|
|
$widgetCount = 0;
|
|
|
|
// Eingaben mit Abständen der Version 1 (zum Beispiel ältere Aufrufer) werden wie beim Lesen übersetzt.
|
|
$migrated = SectionStyle::migrateSpacing(array_map(
|
|
fn ($item) => is_array($item) && array_key_exists('slots', $item) ? $item : ['style' => [], 'slots' => [$item]],
|
|
$items,
|
|
));
|
|
|
|
foreach ($items as $index => $item) {
|
|
if (! is_array($item)) {
|
|
$errors["sections.$index"] = ['Ein Abschnitt ist unvollständig.'];
|
|
|
|
continue;
|
|
}
|
|
|
|
if (! array_key_exists('slots', $item)) {
|
|
$item = ['id' => null, 'layout' => SectionLayouts::DEFAULT, 'style' => [], 'slots' => [$item]];
|
|
} else {
|
|
$item['style'] = $migrated[$index]['style'] ?? ($item['style'] ?? []);
|
|
}
|
|
|
|
$sections[] = $this->normalizeSection($item, $index, $errors, $seenSectionIds, $seenWidgetIds, $widgetCount, $seenAnchors);
|
|
}
|
|
|
|
if ($widgetCount > self::MAX_WIDGETS) {
|
|
$errors['sections'] = ['Eine Seite enthält höchstens '.self::MAX_WIDGETS.' Widgets.'];
|
|
}
|
|
|
|
if ($errors !== []) {
|
|
throw ValidationException::withMessages($errors);
|
|
}
|
|
|
|
return $sections;
|
|
}
|
|
|
|
/**
|
|
* Widgets in Lesereihenfolge (Abschnitt für Abschnitt, Slot für Slot). Wird zusätzlich als flache
|
|
* Bausteinliste gespeichert, damit ein Code-Rollback auf die Fassung vor den Abschnitten die Inhalte
|
|
* weiterhin untereinander darstellt.
|
|
*
|
|
* @param list<array<string, mixed>> $sections
|
|
* @return list<array<string, mixed>>
|
|
*/
|
|
public function flatten(array $sections): array
|
|
{
|
|
$widgets = [];
|
|
|
|
foreach ($sections as $section) {
|
|
$count = SectionLayouts::slotCount($section['layout']);
|
|
|
|
foreach (array_slice($section['slots'], 0, $count) as $widget) {
|
|
if (is_array($widget)) {
|
|
$widgets[] = $widget;
|
|
}
|
|
}
|
|
}
|
|
|
|
return $widgets;
|
|
}
|
|
|
|
/**
|
|
* Öffentliche Medien der Seite: Widget-Bilder und Hintergrundbilder der Abschnitte.
|
|
*
|
|
* @param list<array<string, mixed>> $sections
|
|
* @return list<string>
|
|
*/
|
|
public function mediaPaths(array $sections): array
|
|
{
|
|
$paths = [];
|
|
|
|
foreach ($sections as $section) {
|
|
$style = SectionStyle::fromStored($section['style'] ?? []);
|
|
if (is_string($style['image']) && PublicMedia::isPublicPath($style['image'])) {
|
|
$paths[] = $style['image'];
|
|
}
|
|
}
|
|
|
|
foreach ($this->widgets->mediaPaths($this->flatten($sections)) as $path) {
|
|
$paths[] = $path;
|
|
}
|
|
|
|
return array_values(array_unique($paths));
|
|
}
|
|
|
|
/**
|
|
* @param list<array<string, mixed>> $sections
|
|
*/
|
|
public function pageTitle(array $sections): ?string
|
|
{
|
|
// Ein ausgeblendeter Abschnitt liefert keinen Seitentitel; seine Medien bleiben dagegen erfasst (mediaPaths),
|
|
// damit ihre Bilder nicht als ungenutzt gelten.
|
|
return $this->widgets->pageTitle($this->flatten(array_values(array_filter($sections, fn (array $section): bool => ! ($section['hidden'] ?? false)))));
|
|
}
|
|
|
|
/**
|
|
* @param array<int|string, mixed> $blocks
|
|
* @return list<array{id: ?string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
|
*/
|
|
private function wrapWidgets(array $blocks): array
|
|
{
|
|
$sections = [];
|
|
|
|
foreach ($this->widgets->read($blocks) as $position => $widget) {
|
|
$sections[] = [
|
|
'id' => null,
|
|
'v' => self::VERSION,
|
|
'name' => null,
|
|
'anchor' => null,
|
|
'hidden' => false,
|
|
'layout' => SectionLayouts::DEFAULT,
|
|
// Bestand vor dem Raster stand in einem durchgehenden Blatt: kompakte Abstände, zwischen den Widgets
|
|
// nur einmal (oben kein Abstand ab dem zweiten), wie bisher.
|
|
'style' => ['spacing_top' => $position === 0 ? 'compact' : 'none', 'spacing_bottom' => 'compact', 'gap' => 'normal'] + SectionStyle::DEFAULTS,
|
|
'slots' => [$widget],
|
|
];
|
|
}
|
|
|
|
return $sections;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $section
|
|
* @return array{id: ?string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
|
|
*/
|
|
private function upcastSection(array $section): array
|
|
{
|
|
$layout = SectionLayouts::has($section['layout'] ?? null) ? $section['layout'] : SectionLayouts::DEFAULT;
|
|
$slots = [];
|
|
|
|
foreach (array_values(is_array($section['slots'] ?? null) ? $section['slots'] : []) as $slot) {
|
|
$slots[] = is_array($slot) ? $this->widgets->upcast($slot) : null;
|
|
}
|
|
|
|
while (count($slots) < SectionLayouts::slotCount($layout)) {
|
|
$slots[] = null;
|
|
}
|
|
|
|
return [
|
|
'id' => is_string($section['id'] ?? null) ? $section['id'] : null,
|
|
'v' => self::VERSION,
|
|
'name' => self::cleanName($section['name'] ?? null),
|
|
'anchor' => self::cleanAnchor($section['anchor'] ?? null),
|
|
'hidden' => self::isHidden($section['hidden'] ?? false),
|
|
'layout' => $layout,
|
|
'style' => SectionStyle::fromStored($section['style'] ?? []),
|
|
'slots' => $slots,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $section
|
|
* @param array<string, list<string>> $errors
|
|
* @param array<string, true> $seenSectionIds
|
|
* @param array<string, true> $seenWidgetIds
|
|
* @return array{id: string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
|
|
*/
|
|
private function normalizeSection(array $section, int $index, array &$errors, array &$seenSectionIds, array &$seenWidgetIds, int &$widgetCount, array &$seenAnchors): array
|
|
{
|
|
$prefix = "sections.$index";
|
|
|
|
$layout = $section['layout'] ?? SectionLayouts::DEFAULT;
|
|
if (! SectionLayouts::has($layout)) {
|
|
$errors["$prefix.layout"] = ['Dieses Abschnittsraster ist nicht freigegeben.'];
|
|
$layout = SectionLayouts::DEFAULT;
|
|
}
|
|
|
|
$style = $this->normalizeStyle(is_array($section['style'] ?? null) ? $section['style'] : [], $prefix, $errors);
|
|
|
|
$units = SectionLayouts::units($layout);
|
|
$rawSlots = array_values(is_array($section['slots'] ?? null) ? $section['slots'] : []);
|
|
$filled = count(array_filter($rawSlots, fn ($slot): bool => is_array($slot)));
|
|
|
|
if ($filled > count($units)) {
|
|
$errors["$prefix.slots"] = [sprintf(
|
|
'Das Raster „%s“ hat %d %s, der Abschnitt enthält aber %d Widgets. Entfernen Sie ein Widget oder wählen Sie ein Raster mit mehr Plätzen.',
|
|
SectionLayouts::short($layout),
|
|
count($units),
|
|
count($units) === 1 ? 'Platz' : 'Plätze',
|
|
$filled,
|
|
)];
|
|
} elseif (count($rawSlots) > count($units)) {
|
|
// Überzählige Plätze sind leer: Widgets rücken in Reihenfolge nach vorn, leere Plätze entfallen.
|
|
$rawSlots = array_values(array_filter($rawSlots, fn ($slot): bool => is_array($slot)));
|
|
}
|
|
|
|
$slots = [];
|
|
foreach ($units as $position => $slotUnits) {
|
|
$block = $rawSlots[$position] ?? null;
|
|
|
|
if (! is_array($block)) {
|
|
$slots[] = null;
|
|
|
|
continue;
|
|
}
|
|
|
|
$widgetCount++;
|
|
|
|
try {
|
|
$widget = $this->widgets->normalizeWidget($block, "$prefix.slots.$position", $seenWidgetIds);
|
|
} catch (ValidationException $exception) {
|
|
foreach ($exception->errors() as $key => $messages) {
|
|
$errors[$key] = $messages;
|
|
}
|
|
$slots[] = null;
|
|
|
|
continue;
|
|
}
|
|
|
|
$type = $this->widgets->get($widget['type']);
|
|
if (! $type->supportsUnits($slotUnits)) {
|
|
$errors["$prefix.slots.$position.units"] = [sprintf(
|
|
'„%s“ ist für Plätze mit %s Rastereinheiten vorgesehen; dieser Platz hat %d. Wählen Sie ein passendes Raster oder einen passenden Platz.',
|
|
$type->label(),
|
|
$type->unitsLabel(),
|
|
$slotUnits,
|
|
)];
|
|
}
|
|
|
|
$slots[] = $widget;
|
|
}
|
|
|
|
$id = $section['id'] ?? null;
|
|
if (! is_string($id) || preg_match('/^[A-Za-z0-9-]{1,64}$/', $id) !== 1 || isset($seenSectionIds[$id])) {
|
|
$id = (string) Str::uuid();
|
|
}
|
|
$seenSectionIds[$id] = true;
|
|
|
|
[$name, $anchor] = $this->normalizeLabels($section, $prefix, $errors, $seenAnchors);
|
|
|
|
return [
|
|
'id' => $id,
|
|
'v' => self::VERSION,
|
|
'name' => $name,
|
|
'anchor' => $anchor,
|
|
'hidden' => self::isHidden($section['hidden'] ?? false),
|
|
'layout' => $layout,
|
|
'style' => $style,
|
|
'slots' => $slots,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Name und Sprungmarke eines Abschnitts. Fehler: „sections.N.name“ und „sections.N.anchor“.
|
|
*
|
|
* @param array<string, mixed> $section
|
|
* @param array<string, list<string>> $errors
|
|
* @param array<string, true> $seenAnchors
|
|
* @return array{0: ?string, 1: ?string}
|
|
*/
|
|
private function normalizeLabels(array $section, string $prefix, array &$errors, array &$seenAnchors): array
|
|
{
|
|
$name = null;
|
|
$rawName = $section['name'] ?? null;
|
|
|
|
if (is_string($rawName) && trim($rawName) !== '') {
|
|
$name = self::cleanName($rawName);
|
|
|
|
if ($name === null) {
|
|
$errors["$prefix.name"] = ['Der Name darf höchstens '.self::MAX_NAME.' Zeichen lang sein.'];
|
|
}
|
|
}
|
|
|
|
$anchor = null;
|
|
$rawAnchor = $section['anchor'] ?? null;
|
|
|
|
if (is_string($rawAnchor) && trim($rawAnchor) !== '') {
|
|
$candidate = mb_strtolower(trim($rawAnchor));
|
|
|
|
if (strlen($candidate) > self::MAX_ANCHOR || preg_match(self::ANCHOR_PATTERN, $candidate) !== 1) {
|
|
$errors["$prefix.anchor"] = ['Eine Sprungmarke besteht aus Kleinbuchstaben, Ziffern und einzelnen Bindestrichen (höchstens '.self::MAX_ANCHOR.' Zeichen), zum Beispiel „anmeldung“.'];
|
|
} elseif (in_array($candidate, self::RESERVED_ANCHORS, true) || str_starts_with($candidate, 'bereich-')) {
|
|
$errors["$prefix.anchor"] = ['Diese Sprungmarke ist im Seitengerüst schon vergeben. Bitte eine andere wählen.'];
|
|
} elseif (isset($seenAnchors[$candidate])) {
|
|
$errors["$prefix.anchor"] = ['Diese Sprungmarke gibt es auf der Seite schon. Jede Sprungmarke darf nur einmal vorkommen.'];
|
|
} else {
|
|
$seenAnchors[$candidate] = true;
|
|
$anchor = $candidate;
|
|
}
|
|
} elseif ($rawAnchor !== null && ! is_string($rawAnchor)) {
|
|
$errors["$prefix.anchor"] = ['Die Sprungmarke ist ungültig.'];
|
|
}
|
|
|
|
return [$name, $anchor];
|
|
}
|
|
|
|
/** Interner Name: Leerraum vereinheitlicht, ohne Steuerzeichen; leer oder über 80 Zeichen ergibt null. */
|
|
public static function cleanName(mixed $value): ?string
|
|
{
|
|
if (! is_string($value)) {
|
|
return null;
|
|
}
|
|
|
|
$name = trim((string) preg_replace('/\s+/u', ' ', (string) preg_replace('/[\x00-\x1F\x7F]/u', ' ', $value)));
|
|
|
|
return $name === '' || mb_strlen($name) > self::MAX_NAME ? null : $name;
|
|
}
|
|
|
|
/** Lesepfad: eine gespeicherte Sprungmarke nur, wenn sie der Form entspricht. */
|
|
public static function cleanAnchor(mixed $value): ?string
|
|
{
|
|
return is_string($value) && strlen($value) <= self::MAX_ANCHOR && preg_match(self::ANCHOR_PATTERN, $value) === 1
|
|
&& ! in_array($value, self::RESERVED_ANCHORS, true) && ! str_starts_with($value, 'bereich-')
|
|
? $value
|
|
: null;
|
|
}
|
|
|
|
public static function isHidden(mixed $value): bool
|
|
{
|
|
return $value === true || $value === 1 || $value === '1' || $value === 'true';
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $style
|
|
* @param array<string, list<string>> $errors
|
|
* @return array<string, mixed>
|
|
*/
|
|
private function normalizeStyle(array $style, string $prefix, array &$errors): array
|
|
{
|
|
$result = SectionStyle::DEFAULTS;
|
|
$enums = SectionStyle::enums();
|
|
|
|
foreach ($style as $key => $value) {
|
|
if ($key === 'image' || str_starts_with((string) $key, '_')) {
|
|
continue;
|
|
}
|
|
|
|
if (! isset($enums[$key])) {
|
|
$errors["$prefix.style.$key"] = ['Diese Gestaltungsoption ist nicht freigegeben.'];
|
|
|
|
continue;
|
|
}
|
|
|
|
if ($value === null || $value === '') {
|
|
continue;
|
|
}
|
|
|
|
if (! is_string($value) || ! array_key_exists($value, $enums[$key])) {
|
|
$errors["$prefix.style.$key"] = ['Dieser Gestaltungswert ist nicht freigegeben.'];
|
|
|
|
continue;
|
|
}
|
|
|
|
$result[$key] = $value;
|
|
}
|
|
|
|
if ($result['background'] === 'image') {
|
|
$widgetErrors = new WidgetErrors;
|
|
$refs = ImageRefFields::clean(['image' => $style['image'] ?? null, '_upload' => $style['_upload'] ?? null], $widgetErrors, errorKey: 'image');
|
|
$image = $refs['image'];
|
|
|
|
foreach ($widgetErrors->all() as $messages) {
|
|
$errors["$prefix.style.image"] = $messages;
|
|
}
|
|
|
|
if ($image === null && ! isset($errors["$prefix.style.image"])) {
|
|
$errors["$prefix.style.image"] = ['Bitte ein Hintergrundbild aus dem Medienmanager wählen oder hochladen.'];
|
|
}
|
|
|
|
$result['image'] = $image;
|
|
} else {
|
|
$result['image'] = null;
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
}
|