Loheide-eu-mitarbeiterplatt.../app/Pagebuilder/Content.php
Friederich Loheide 2b5fe55f8e
All checks were successful
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m40s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m23s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m53s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m47s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 3m2s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 3m5s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 2m50s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 2m41s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m6s
MySQL: JSON-Schlüsselreihenfolge darf keine Rolle spielen
MySQL speichert Schlüssel in JSON-Spalten sortiert, MariaDB unverändert.
- Seiten: „Stand unverändert → kein Entwurf“ vergleicht jetzt unabhängig von der
  Schlüsselreihenfolge (auf MySQL entstand sonst bei jedem Speichern ein Entwurf)
- Formulare: Antworten in Ergebnisansicht und E-Mail in der Reihenfolge des Formulars
- Tests vergleichen assoziative Arrays ohne Reihenfolge; neue Tests dafür

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 11:22:46 +00:00

317 lines
9.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Pagebuilder;
use App\Models\User;
use App\Support\Permissions\Audiences;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Throwable;
/**
* Inhalt einer Seite: ein Baum aus Blöcken.
*
* {"blocks": [{"id": "…", "type": "columns", "data": {…}, "visibility": {…},
* "items": [{"id": "…", "title": "…", "blocks": [ … ]}]}]}
*
* sanitize() läuft beim Speichern: unbekannte Blöcke und Felder fallen weg,
* HTML wird bereinigt, Adressen geprüft. render() läuft bei der Anzeige:
* blendet Blöcke nach Sichtbarkeit aus und ergänzt dynamische Daten.
*/
class Content
{
public const MAX_DEPTH = 6;
public const MAX_BLOCKS = 800;
private int $count = 0;
public function __construct(private readonly Blocks $blocks) {}
/**
* @return array{blocks: list<array<string, mixed>>}
*/
public static function empty(): array
{
return ['blocks' => []];
}
/**
* @param array<mixed>|null $content
* @return array{blocks: list<array<string, mixed>>}
*/
public function sanitize(?array $content): array
{
$this->count = 0;
return ['blocks' => $this->sanitizeList($content['blocks'] ?? [], 1)];
}
/**
* Anzeigefertiger Inhalt für eine Person.
*
* @param array<mixed>|null $content bereits bereinigter Inhalt
* @return array{blocks: list<array<string, mixed>>}
*/
public function render(?array $content, ?User $user, array $context = []): array
{
return ['blocks' => $this->renderList($content['blocks'] ?? [], $user, $context)];
}
/**
* Ein einzelner Block (Editor-Vorschau dynamischer Blöcke).
*
* @param array<mixed> $block
* @return array<string, mixed>|null
*/
public function preview(array $block, ?User $user, array $context = []): ?array
{
$this->count = 0;
$clean = $this->sanitizeList([$block], 1)[0] ?? null;
if (! $clean) {
return null;
}
$type = $this->blocks->get($clean['type']);
return $type?->resolve ? $this->resolve($type, $clean, $user, $context) : [];
}
/**
* Gleicher Inhalt? Unabhängig von der Reihenfolge der Schlüssel – MySQL
* sortiert Schlüssel in JSON-Spalten um, MariaDB nicht.
*
* @param array<mixed>|null $a
* @param array<mixed>|null $b
*/
public static function same(?array $a, ?array $b): bool
{
return self::canonical($a) === self::canonical($b);
}
private static function canonical(mixed $value): mixed
{
if (! is_array($value)) {
return $value;
}
if (! array_is_list($value)) {
ksort($value);
}
return array_map(self::canonical(...), $value);
}
/**
* Alle Werte eines Feldtyps im Baum, z. B. alle Bildpfade (für Aufräumarbeiten).
*
* @param array<mixed>|null $content
* @return list<mixed>
*/
public function collect(?array $content, callable $picker): array
{
$result = [];
$walk = function (array $blocks) use (&$walk, &$result, $picker) {
foreach ($blocks as $block) {
array_push($result, ...(array) $picker($block));
foreach ($block['items'] ?? [] as $item) {
$walk($item['blocks'] ?? []);
}
}
};
$walk($content['blocks'] ?? []);
return $result;
}
/**
* Reiner Text des Inhalts, z. B. für die Suche.
*
* @param array<mixed>|null $content
*/
public function plainText(?array $content): string
{
$parts = $this->collect($content, function (array $block) {
$texts = [];
array_walk_recursive($block['data'], function ($value) use (&$texts) {
if (is_string($value) && ! str_starts_with($value, 'pagebuilder/')) {
$texts[] = strip_tags($value);
}
});
foreach ($block['items'] ?? [] as $item) {
$texts[] = $item['title'] ?? '';
}
return [implode(' ', $texts)];
});
return trim(preg_replace('/\s+/u', ' ', html_entity_decode(implode(' ', $parts))) ?? '');
}
/**
* @return list<array<string, mixed>>
*/
private function sanitizeList(mixed $blocks, int $depth): array
{
if (! is_array($blocks) || $depth > self::MAX_DEPTH) {
return [];
}
$result = [];
foreach (array_values($blocks) as $block) {
if (! is_array($block) || ++$this->count > self::MAX_BLOCKS) {
continue;
}
$type = $this->blocks->get((string) ($block['type'] ?? ''));
if (! $type) {
continue;
}
$data = is_array($block['data'] ?? null) ? $block['data'] : [];
$clean = [
'id' => self::id($block['id'] ?? null),
'type' => $type->key,
'data' => [],
];
foreach ($type->fields as $field) {
$clean['data'][$field->name] = $field->sanitize(array_key_exists($field->name, $data) ? $data[$field->name] : $field->default());
}
$visibility = $this->sanitizeVisibility($block['visibility'] ?? null);
if ($visibility !== null) {
$clean['visibility'] = $visibility;
}
if ($type->container) {
$clean['items'] = $this->sanitizeItems($type, $clean['data'], $block['items'] ?? [], $depth);
}
$result[] = $clean;
}
return $result;
}
/**
* @param array<string, mixed> $data
* @return list<array<string, mixed>>
*/
private function sanitizeItems(BlockType $type, array $data, mixed $items, int $depth): array
{
$items = is_array($items) ? array_values(array_filter($items, 'is_array')) : [];
$container = $type->container;
// Spalten: Anzahl folgt der Aufteilung. Überzählige Spalten werden an die letzte angehängt, nichts geht verloren.
$count = $type->key === 'columns'
? count(explode('-', (string) ($data['layout'] ?? '1-1')))
: max($container['min'], min($container['max'], count($items)));
if (count($items) > $count && $count > 0) {
$overflow = array_merge(...array_map(fn ($item) => (array) ($item['blocks'] ?? []), array_slice($items, $count)));
$items = array_slice($items, 0, $count);
$items[$count - 1]['blocks'] = array_merge((array) ($items[$count - 1]['blocks'] ?? []), $overflow);
}
$items = array_pad($items, $count, []);
return array_map(fn (array $item) => array_filter([
'id' => self::id($item['id'] ?? null),
'title' => $container['titled'] ? mb_substr(trim((string) ($item['title'] ?? '')), 0, 120) : null,
'blocks' => $this->sanitizeList($item['blocks'] ?? [], $depth + 1),
], fn ($value) => $value !== null), $items);
}
/**
* @return array{role?: list<string>, department?: list<string>, location?: list<string>}|null
*/
private function sanitizeVisibility(mixed $visibility): ?array
{
if (! is_array($visibility)) {
return null;
}
$clean = [];
foreach (['role', 'department', 'location'] as $rule) {
$values = array_values(array_unique(array_filter(array_map(
fn ($value) => is_scalar($value) ? mb_substr(trim((string) $value), 0, 150) : '',
(array) ($visibility[$rule] ?? []),
))));
if ($values !== []) {
$clean[$rule] = array_slice($values, 0, 50);
}
}
return $clean === [] ? null : $clean;
}
/**
* @param list<array<string, mixed>> $blocks
* @return list<array<string, mixed>>
*/
private function renderList(array $blocks, ?User $user, array $context): array
{
$result = [];
foreach ($blocks as $block) {
$type = $this->blocks->get($block['type'] ?? '');
// Blöcke deaktivierter Plugins und fremde Zielgruppen einfach auslassen.
if (! $type || ! Audiences::matches($block['visibility'] ?? null, $user)) {
continue;
}
if ($type->resolve) {
$props = $this->resolve($type, $block, $user, $context);
if ($props === null) {
continue;
}
$block['props'] = $props;
}
unset($block['visibility']);
$block['component'] = $type->component;
if (isset($block['items'])) {
$block['items'] = array_map(fn (array $item) => [...$item, 'blocks' => $this->renderList($item['blocks'] ?? [], $user, $context)], $block['items']);
}
$result[] = $block;
}
return $result;
}
/**
* @param array<string, mixed> $block
* @return array<string, mixed>|null
*/
private function resolve(BlockType $type, array $block, ?User $user, array $context): ?array
{
try {
return ($type->resolve)($block['data'], $user, $context);
} catch (Throwable $e) {
// Ein fehlerhafter Plugin-Block darf die Seite nicht mitreißen.
Log::warning("Pagebuilder-Block {$type->key} konnte nicht geladen werden: ".$e->getMessage());
return null;
}
}
private static function id(mixed $id): string
{
return is_string($id) && preg_match('/^[A-Za-z0-9_-]{4,40}$/', $id) ? $id : Str::random(12);
}
}