*/ private array $types = []; /** * @param iterable $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."); } 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 */ public function all(): array { return $this->types; } /** * @return array */ 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 $block * @return array{id: ?string, type: string, v: int, variant: string, settings: array, data: array, refs: array}|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 Bausteine für eine neue Revision. * * @param array $blocks * @return list, data: array, refs: array}> */ public function normalize(array $blocks): array { $normalized = []; $seenIds = []; foreach (array_values($blocks) as $index => $block) { if (! is_array($block)) { throw ValidationException::withMessages([ "blocks.$index" => 'Ein Baustein ist unvollständig.', ]); } if (! $this->has($block['type'] ?? null)) { throw ValidationException::withMessages([ "blocks.$index.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([ "blocks.$index.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([ "blocks.$index.variant" => 'Diese Darstellungsvariante ist für den Baustein nicht freigegeben.', ]); } $widget = $this->upcast($block); $normalized[] = $this->validateOne($type, $widget, $index, $seenIds); } return $normalized; } /** * Gespeicherte Bausteine einer Revision als aktuelle Hüllen; unbekannte Arten entfallen. * * @param array|null $blocks * @return list> */ 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|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|null $blocks * @return list */ 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 $widget * @param array $seenIds * @return array{id: string, type: string, v: int, variant: string, settings: array, data: array, refs: array} */ private function validateOne(WidgetType $type, array $widget, int $index, 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->settings(); 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["blocks.$index.$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 $values * @param array $rules * @return array */ 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 $values * @return array */ private function withoutTransient(array $values): array { foreach (array_keys($values) as $key) { if (str_starts_with((string) $key, '_')) { unset($values[$key]); } } return $values; } }