Files
laraundfelix/app/Domain/Cms/Sections/PageSections.php
T
LarsandClaude Opus 5.5 f511ad10de
CI Feature / test (push) Successful in 42s
Deploy Test / test (push) Successful in 37s
Deploy Test / deploy (push) Successful in 31s
Vereinfache die Abschnittsabstände auf oben, unten und Widget-Abstand.
Die Abschnittshülle Version 2 kennt genau drei unabhängige Abstände mit
denselben Stufen (Kein Abstand, Kompakt, Normal, Großzügig):
- spacing_top / spacing_bottom: Innenabstand des Abschnitts; zwischen
  zwei Abschnitten addieren sich unten und oben (0 + 0 = 0).
- gap: Abstand zwischen den Plätzen des Rasters, nebeneinander und
  gestapelt. Widget-Innenabstände bleiben im Widget.

Entfallen sind „Abstand oben und unten“, die Abweichung „Abstand oben“
(same/small/none), die versteckte Regel, die oben zwischen zwei
Abschnitten ohne Fläche auf null setzte, und der Trenner „Zusätzlicher
Abstand“.

Hüllen der Version 1 werden beim Lesen ohne Layoutänderung übersetzt
(SectionStyle::migrateSpacing); gespeicherte Revisionen bleiben. Einzige
Abweichung: „Gering“ hat keine eigene Stufe mehr und wird „Kompakt“.

Tests bewusst angepasst (Hüllenversion 2, neue Klassen, Prüfung freier
Werte über die neuen Schlüssel); neue Tests für Addition, Vorgaben und
die Übersetzung aller Fälle der Version 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:39:57 +01:00

356 lines
13 KiB
PHP

<?php
namespace App\Domain\Cms\Sections;
use App\Domain\Cms\Widgets\Support\PublicMedia;
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.
*
* 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 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, 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, 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 = [];
$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);
}
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 ($style['image'] !== null && 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
{
return $this->widgets->pageTitle($this->flatten($sections));
}
/**
* @param array<int|string, mixed> $blocks
* @return list<array{id: ?string, v: int, 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,
'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, 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,
'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, 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
{
$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;
return [
'id' => $id,
'v' => self::VERSION,
'layout' => $layout,
'style' => $style,
'slots' => $slots,
];
}
/**
* @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;
}
$upload = PublicMedia::fromUploadState($style['_upload'] ?? null);
$image = $upload ?? PublicMedia::fromUploadState($style['image'] ?? null);
if ($result['background'] === 'image') {
if ($image === null) {
$errors["$prefix.style.image"] = ['Bitte ein Hintergrundbild wählen oder hochladen.'];
} elseif (! PublicMedia::isPublicPath($image)) {
$errors["$prefix.style.image"] = ['Das Hintergrundbild liegt nicht im öffentlichen Medienbereich.'];
}
$result['image'] = $image;
} else {
$result['image'] = null;
}
return $result;
}
}