Files
laraundfelix/app/Domain/Cms/Widgets/WidgetRegistry.php
T
LarsandClaude Sonnet 5.5 2b00905f00
CI Feature / test (push) Failing after 5m29s
Ergänze Farbe aus der Palette und Schriftgrößen je Widget
Gemeinsamer Vertrag in WidgetType (typography(), paletteTarget()) mit den
Einstellungen heading_size, text_size und palette; WidgetAppearance setzt
Klassen und Eigenschaften an der Hülle, nur wenn ein Wert gewählt ist.
Eine absolute Größenskala aus den Designwerten gilt in jedem Widget gleich;
ohne Wahl bleibt die bisherige Größe. Die Palettenfarbe färbt je Art die
Fläche des Widgets (hull) oder dessen eigene Fläche (face).

Der Verwendungsnachweis der Palette zählt jetzt auch Widgets, damit die
Bestätigung einer Farbänderung und die Sperre beim Entfernen greifen.
Der Vertragstest für Einstellungsgruppen nimmt die gemeinsamen Schlüssel
bewusst aus, weil sie eigene Gruppen im Editor haben.

ADR-68, Abnahme unter docs/ux/verwaltung/abnahme/widget-flaeche-schrift.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-30 09:50:16 +01:00

415 lines
14 KiB
PHP

<?php
namespace App\Domain\Cms\Widgets;
use App\Domain\Cms\Widgets\Support\WidgetAppearance;
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 (array_intersect(array_keys($type->settings()), WidgetAppearance::KEYS) !== []) {
throw new InvalidArgumentException("Widget „{$key}“ deklariert Schriftgröße oder Farbe über typography() und paletteTarget(), nicht über settings().");
}
if (array_diff($type->typography(), ['heading', 'text']) !== [] || ! in_array($type->paletteTarget(), [null, 'hull', 'face'], true)) {
throw new InvalidArgumentException("Widget „{$key}“ verwendet eine unbekannte Schrift- oder Farbangabe.");
}
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;
}
}