Files
laraundfelix/app/Domain/Cms/Widgets/WidgetRegistry.php
LarsandClaude Opus 5.5 0bfb53463a
CI Feature / test (push) Successful in 41s
Deploy Test / test (push) Successful in 37s
Deploy Test / deploy (push) Successful in 33s
Führe einen gemeinsamen Layoutvertrag ein und integriere die Premium-Widgets.
Layoutvertrag (ADR-38) in der bestehenden Registry: Jede Widget-Art
erklärt zulässige Rasterbreiten (supportedUnits), Höhen aus einem
gemeinsamen Vokabular (heights, gespeichert als settings.height),
Darstellungsmodi und Verhalten bei wenig Platz. Unzulässige Breiten
werden beim Speichern verständlich abgewiesen; Höhe „fill“ streckt
den Handlungsaufruf auf die Abschnittszeile.

Premium-Widgets nach Brand-UI-Kit v1.6:
- hero Version 2: photo_split/editorial_solid, Höhen compact/normal/
  large, Label, Überschriftenebene, Akzent, Bildfokus in Prozent, zwei
  Schaltflächen; nur 3 oder 4 Einheiten. Upgrade aus Version 1.
- image_text Version 3: Fläche cream/clear/navy, Höhen compact/normal/
  spacious, Label, zwei Schaltflächen, Bildfokus; 1 bis 4 Einheiten.
  Upgrade aus Version 2 (format entfällt, Fokus in Prozent).
- Kit-CSS ersetzt das bisherige Hero- und Bild-und-Text-CSS; der
  Randlos-Mechanismus der Designiteration 1 entfällt.

Editor: Reiter Inhalt/Medien/Darstellung aus der Registry, Auswahl-
knöpfe mit Symbolen, Schieberegler für den Bildfokus und eine Live-
Vorschau im Dialog mit demselben Renderer in wählbarer Platzbreite.

Tests bewusst angepasst: Einstieg braucht jetzt 3 oder 4 Einheiten
(vorher Mindestbreite 2), image_text ist Version 3, Klassen der neuen
Ansichten; die Hero-/Bild-Tests der Designiteration 1 sind durch
CmsPremiumWidgetsTest ersetzt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:20:09 +01:00

406 lines
14 KiB
PHP

<?php
namespace App\Domain\Cms\Widgets;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
/**
* Zentrales, codebasiertes Widget-Register (ADR-30).
*
* Lesepfad: upcast() hebt jeden gespeicherten Baustein (Altformat ohne Hülle oder Hülle älterer Version)
* auf die aktuelle Hülle an, ohne die gespeicherte Revision zu verändern.
* Schreibpfad: normalize() prüft und bereinigt Bausteine aus dem Editor und liefert Hüllen der aktuellen Version.
*/
class WidgetRegistry
{
/** @var array<string, WidgetType> */
private array $types = [];
/**
* @param iterable<WidgetType> $types
*/
public function __construct(iterable $types = [])
{
foreach ($types as $type) {
$this->register($type);
}
}
public function register(WidgetType $type): void
{
$key = $type->key();
if (preg_match('/^[a-z][a-z0-9_]{1,40}$/', $key) !== 1) {
throw new InvalidArgumentException("Ungültige Widget-Kennung „{$key}“.");
}
if (isset($this->types[$key])) {
throw new InvalidArgumentException("Die Widget-Kennung „{$key}“ ist bereits registriert.");
}
if ($type->version() < 1) {
throw new InvalidArgumentException("Widget „{$key}“ braucht eine Schemaversion ab 1.");
}
// Gemeinsamer Layoutvertrag (ADR-38): Breiten, Vorzugsbreite und Höhen aus festen Wertebereichen.
$units = $type->supportedUnits();
if ($units === [] || array_diff($units, [1, 2, 3, 4]) !== [] || $units !== array_values(array_unique($units)) || ! $type->supportsUnits($type->preferredUnits())) {
throw new InvalidArgumentException("Widget „{$key}“ braucht unterstützte Breiten zwischen 1 und 4 Rastereinheiten und eine darin enthaltene Vorzugsbreite.");
}
if (array_diff(array_keys($type->heights()), array_keys(WidgetType::HEIGHTS)) !== []) {
throw new InvalidArgumentException("Widget „{$key}“ verwendet eine Höhe außerhalb des gemeinsamen Vokabulars.");
}
if (array_key_exists('height', $type->settings())) {
throw new InvalidArgumentException("Widget „{$key}“ deklariert die Höhe über heights(), nicht über settings().");
}
if ($type->variants() === []) {
throw new InvalidArgumentException("Widget „{$key}“ braucht mindestens eine Darstellungsvariante.");
}
foreach (array_keys($type->variants()) as $variant) {
if (preg_match('/^[a-z][a-z0-9_]*$/', (string) $variant) !== 1) {
throw new InvalidArgumentException("Widget „{$key}“ hat eine ungültige Variantenkennung.");
}
}
$this->types[$key] = $type;
}
public function has(mixed $key): bool
{
return is_string($key) && isset($this->types[$key]);
}
public function get(string $key): WidgetType
{
return $this->types[$key] ?? throw new InvalidArgumentException("Unbekannte Widget-Art „{$key}“.");
}
/**
* @return array<string, WidgetType>
*/
public function all(): array
{
return $this->types;
}
/**
* @return array<string, string>
*/
public function labels(): array
{
return array_map(fn (WidgetType $type): string => $type->label(), $this->types);
}
/**
* Hebt einen gespeicherten Baustein auf die aktuelle Hülle an. Unbekannte Arten liefern null.
*
* @param array<string, mixed> $block
* @return array{id: ?string, type: string, v: int, variant: string, settings: array<string, mixed>, data: array<string, mixed>, refs: array<string, mixed>}|null
*/
public function upcast(array $block): ?array
{
$key = $block['type'] ?? null;
if (! $this->has($key)) {
return null;
}
$type = $this->get($key);
if (array_key_exists('v', $block)) {
$widget = [
'id' => is_string($block['id'] ?? null) ? $block['id'] : null,
'type' => $key,
'v' => max(1, (int) $block['v']),
'variant' => is_string($block['variant'] ?? null) ? $block['variant'] : $type->defaultVariant(),
'settings' => is_array($block['settings'] ?? null) ? $block['settings'] : [],
'data' => is_array($block['data'] ?? null) ? $block['data'] : [],
'refs' => is_array($block['refs'] ?? null) ? $block['refs'] : [],
];
} else {
$legacy = $type->fromLegacy($block);
$widget = [
'id' => null,
'type' => $key,
'v' => 1,
'variant' => $legacy['variant'] ?? $type->defaultVariant(),
'settings' => [],
'data' => $legacy['data'],
'refs' => $legacy['refs'],
];
}
while ($widget['v'] < $type->version()) {
$from = $widget['v'];
$widget = $type->upgrade($widget, $from);
$widget['v'] = $from + 1;
}
if (! array_key_exists($widget['variant'], $type->variants())) {
$widget['variant'] = $type->defaultVariant();
}
return $widget;
}
/**
* Prüft und bereinigt eine flache Bausteinliste (Fehlerschlüssel "blocks.N…").
*
* @param array<int|string, mixed> $blocks
* @return list<array{id: string, type: string, v: int, variant: string, settings: array<string, mixed>, data: array<string, mixed>, refs: array<string, mixed>}>
*/
public function normalize(array $blocks): array
{
$normalized = [];
$seenIds = [];
foreach (array_values($blocks) as $index => $block) {
$normalized[] = $this->normalizeWidget($block, "blocks.$index", $seenIds);
}
return $normalized;
}
/**
* Prüft und bereinigt einen einzelnen Baustein für eine neue Revision. Der Aufrufer führt die Menge
* bereits vergebener Kennungen über die ganze Seite, damit kopierte Widgets neue Kennungen erhalten.
*
* @param array<string, true> $seenIds
* @return array{id: string, type: string, v: int, variant: string, settings: array<string, mixed>, data: array<string, mixed>, refs: array<string, mixed>}
*/
public function normalizeWidget(mixed $block, string $errorPrefix, array &$seenIds): array
{
if (! is_array($block)) {
throw ValidationException::withMessages([
$errorPrefix => 'Ein Baustein ist unvollständig.',
]);
}
if (! $this->has($block['type'] ?? null)) {
throw ValidationException::withMessages([
"$errorPrefix.type" => 'Dieser Bausteintyp ist nicht freigegeben.',
]);
}
$type = $this->get($block['type']);
if (array_key_exists('v', $block) && (int) $block['v'] > $type->version()) {
throw ValidationException::withMessages([
"$errorPrefix.v" => 'Dieser Baustein stammt aus einer neueren Programmfassung und kann hier nicht gespeichert werden.',
]);
}
$requested = $block['variant'] ?? null;
$isCurrent = array_key_exists('v', $block) && (int) $block['v'] === $type->version();
if ($isCurrent && is_string($requested) && $requested !== '' && ! array_key_exists($requested, $type->variants())) {
throw ValidationException::withMessages([
"$errorPrefix.variant" => 'Diese Darstellungsvariante ist für den Baustein nicht freigegeben.',
]);
}
return $this->validateOne($type, $this->upcast($block), $errorPrefix, $seenIds);
}
/**
* Gespeicherte Bausteine einer Revision als aktuelle Hüllen; unbekannte Arten entfallen.
*
* @param array<int|string, mixed>|null $blocks
* @return list<array<string, mixed>>
*/
public function read(?array $blocks): array
{
$widgets = [];
foreach (array_values($blocks ?? []) as $block) {
if (is_array($block) && ($widget = $this->upcast($block)) !== null) {
$widgets[] = $widget;
}
}
return $widgets;
}
/**
* @param array<int|string, mixed>|null $blocks
*/
public function pageTitle(?array $blocks): ?string
{
foreach ($this->read($blocks) as $widget) {
$title = $this->get($widget['type'])->pageTitle($widget);
if (is_string($title) && trim($title) !== '') {
return $title;
}
}
return null;
}
/**
* @param array<int|string, mixed>|null $blocks
* @return list<string>
*/
public function mediaPaths(?array $blocks): array
{
$paths = [];
foreach ($this->read($blocks) as $widget) {
foreach ($this->get($widget['type'])->mediaPaths($widget) as $path) {
$paths[] = $path;
}
}
return array_values(array_unique($paths));
}
/**
* @param array<string, mixed> $widget
* @param array<string, true> $seenIds
* @return array{id: string, type: string, v: int, variant: string, settings: array<string, mixed>, data: array<string, mixed>, refs: array<string, mixed>}
*/
private function validateOne(WidgetType $type, array $widget, string $errorPrefix, array &$seenIds): array
{
$errors = new WidgetErrors;
$variant = $widget['variant'];
if (! array_key_exists($variant, $type->variants())) {
$errors->add('variant', 'Diese Darstellungsvariante ist für den Baustein nicht freigegeben.');
}
$settings = [];
$allowedSettings = $type->settingOptions();
foreach ($widget['settings'] as $key => $value) {
if ($value === null || $value === '') {
continue;
}
if (! isset($allowedSettings[$key]) || ! is_string($value) || ! array_key_exists($value, $allowedSettings[$key])) {
$errors->add("settings.$key", 'Diese Einstellung ist für den Baustein nicht freigegeben.');
continue;
}
$settings[$key] = $value;
}
$rules = [];
foreach ($type->dataRules() as $key => $rule) {
$rules["data.$key"] = $rule;
}
foreach ($type->refRules() as $key => $rule) {
$rules["refs.$key"] = $rule;
}
$validator = Validator::make(['data' => $widget['data'], 'refs' => $widget['refs']], $rules);
foreach ($validator->errors()->messages() as $key => $messages) {
foreach ($messages as $message) {
$errors->add($key, $message);
}
}
$data = $this->onlyDeclared($widget['data'], $type->dataRules());
$refs = $this->onlyDeclared($widget['refs'], $type->refRules());
if ($errors->isEmpty()) {
[$data, $refs] = $type->clean($data, $refs, $errors);
}
if (! $errors->isEmpty()) {
$messages = [];
foreach ($errors->all() as $key => $list) {
$messages["$errorPrefix.$key"] = $list;
}
throw ValidationException::withMessages($messages);
}
$id = $widget['id'];
if (! is_string($id) || preg_match('/^[A-Za-z0-9-]{1,64}$/', $id) !== 1 || isset($seenIds[$id])) {
$id = (string) Str::uuid();
}
$seenIds[$id] = true;
return [
'id' => $id,
'type' => $type->key(),
'v' => $type->version(),
'variant' => $variant,
'settings' => $settings,
'data' => $this->withoutTransient($data),
'refs' => $this->withoutTransient($refs),
];
}
/**
* Behält nur Schlüssel, für die Prüfregeln bestehen; Listen ('items.*.feld') werden je Eintrag gefiltert.
*
* @param array<string, mixed> $values
* @param array<string, mixed> $rules
* @return array<string, mixed>
*/
private function onlyDeclared(array $values, array $rules): array
{
$top = [];
$nested = [];
foreach (array_keys($rules) as $key) {
if (preg_match('/^([a-z_]+)\.\*\.([a-z_]+)$/', (string) $key, $match) === 1) {
$nested[$match[1]][] = $match[2];
} elseif (! str_contains((string) $key, '.')) {
$top[] = (string) $key;
}
}
$clean = [];
foreach ($top as $key) {
$value = $values[$key] ?? null;
if (isset($nested[$key])) {
$items = [];
foreach (array_values(is_array($value) ? $value : []) as $item) {
if (! is_array($item)) {
continue;
}
$entry = [];
foreach ($nested[$key] as $field) {
$entry[$field] = $item[$field] ?? null;
}
$items[] = $entry;
}
$value = $items;
}
$clean[$key] = $value;
}
return $clean;
}
/**
* Felder mit führendem Unterstrich (zum Beispiel '_upload') sind reine Editorhilfen und werden nicht gespeichert.
*
* @param array<string, mixed> $values
* @return array<string, mixed>
*/
private function withoutTransient(array $values): array
{
foreach (array_keys($values) as $key) {
if (str_starts_with((string) $key, '_')) {
unset($values[$key]);
}
}
return $values;
}
}