Files
laraundfelix/tests/Unit/WidgetRegistryTest.php
T
LarsandClaude Opus 5.5 9d936bfa4a
CI Feature / test (push) Successful in 31s
Führe eine zentrale Widget-Registry mit visuellem Seiteneditor ein.
- Codebasiertes Widget-Register (config/cms.php) mit Vertrag
  {id, type, v, variant, settings, data, refs}: Typkennung, Schemaversion,
  Prüfregeln, freigegebene Varianten, Editorfelder, Blade-Ansicht,
  Verweisauflösung und Medienliste je Widget-Art.
- Die sechs Bestandsbausteine bleiben als Version 1 lesbar; gespeicherte
  Revisionen werden nicht umgeschrieben, sondern beim Lesen angehoben
  (Bild und Text: Version 2 mit Titel, formatiertem Text, Bild links/rechts).
  Wiederherstellen kopiert eine Revision unverändert.
- Neue Widgets: Einstieg (Hero) und Programm-/Modulkarten. Letztere speichern
  nur Verweise; Titel und Kurzbeschreibung kommen aus den Fachdaten. Öffentlich
  erscheinen nur Programme mit Anzeigefreigabe (gleiche Regel wie /programme,
  jetzt in PublicCatalogReader); Module nur in der Redaktionsvorschau, bis
  öffentliche Profile (ADR-29) bestehen.
- Ein Renderer für öffentliche Seite, Vorschau und Blockvorschau im Editor.
- Seiteneditor als Filament-Builder: Auswahl mit Beschreibung und Schema,
  kompakte Abschnitte mit Vorschau, Bearbeitung im Dialog, Sortieren,
  Duplizieren. Speichern erzeugt nur einen Entwurf.
- Vorschau einer Revision in 390/768/1440 px; Vorschauroute nutzt den
  Personal-Guard (vorher war sie für Redakteure ohne Mitgliedersitzung
  nicht erreichbar).
- Basislayout in Komponenten (Marke, Kopf, Fuß, Seitenvorlage).
- Navigation: bearbeiten, ausblenden, löschen, per Ziehen sortieren;
  unsichere Adressen (javascript:) werden abgewiesen und nicht ausgegeben.
  Ergänzende Migration is_visible (Vorgabe sichtbar).
- Pfadfehler und doppelte Pfade erscheinen am Pfadfeld statt still zu scheitern.

Tests: BlockRegistryTest geht in WidgetRegistryTest auf (gleiche Prüfungen
plus Registrierung, Versionierung, Bereinigung). Bestandsseiten werden gegen
Textfixtures aus dem Stand vor der Umstellung geprüft.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:49:30 +01:00

319 lines
12 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 Tests\Unit;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\RichText;
use App\Domain\Cms\Widgets\WidgetRegistry;
use App\Domain\Cms\Widgets\WidgetRenderer;
use App\Domain\Cms\Widgets\WidgetType;
use App\Filament\Support\WidgetEditor;
use Filament\Forms\Components\TextInput;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use Tests\TestCase;
class WidgetRegistryTest extends TestCase
{
private function registry(): WidgetRegistry
{
return app(WidgetRegistry::class);
}
public function test_all_configured_widgets_are_registered_with_complete_contract(): void
{
$types = $this->registry()->all();
$this->assertSame(
['hero', 'heading', 'prose', 'image_text', 'cards', 'catalog_cards', 'call_to_action', 'faq'],
array_keys($types),
);
foreach ($types as $key => $type) {
$this->assertSame($key, $type->key());
$this->assertNotSame('', $type->label());
$this->assertNotSame('', $type->description());
$this->assertGreaterThanOrEqual(1, $type->version());
$this->assertNotEmpty($type->variants());
$this->assertArrayHasKey($type->defaultVariant(), $type->variants());
$this->assertNotEmpty($type->dataRules());
$this->assertNotEmpty($type->editorSchema());
$this->assertTrue(view()->exists($type->view()), "Ansicht für $key fehlt");
}
}
public function test_reference_widgets_offer_at_least_two_variants(): void
{
foreach (['hero', 'image_text', 'cards', 'catalog_cards'] as $key) {
$this->assertGreaterThanOrEqual(2, count($this->registry()->get($key)->variants()), $key);
}
$this->assertSame(['image_left', 'image_right'], array_keys($this->registry()->get('image_text')->variants()));
}
public function test_registration_rejects_duplicate_and_invalid_keys(): void
{
$registry = new WidgetRegistry([$this->customWidget('teaser')]);
$this->expectException(InvalidArgumentException::class);
$registry->register($this->customWidget('teaser'));
}
public function test_registration_rejects_keys_that_are_not_stable_identifiers(): void
{
$this->expectException(InvalidArgumentException::class);
new WidgetRegistry([$this->customWidget('Teaser Box')]);
}
public function test_a_new_widget_type_works_through_the_contract_alone(): void
{
$registry = new WidgetRegistry([$this->customWidget('teaser')]);
$this->app->instance(WidgetRegistry::class, $registry);
$stored = $registry->normalize([
['type' => 'teaser', 'v' => 1, 'variant' => 'wide', 'data' => ['heading' => 'Neu']],
]);
$this->assertSame('teaser', $stored[0]['type']);
$this->assertSame('wide', $stored[0]['variant']);
$this->assertSame(['heading' => 'Neu'], $stored[0]['data']);
$html = app(WidgetRenderer::class)->renderAll($stored, RenderContext::publicPage())->toHtml();
$this->assertStringContainsString('<h1>Neu</h1>', $html);
$this->assertStringContainsString('widget-variant-wide', $html);
$block = WidgetEditor::block($registry->get('teaser'));
$this->assertSame('teaser', $block->getName());
$this->assertSame('Teaser · Breit – Neu', (string) $block->getLabel(['variant' => 'wide', 'data' => ['heading' => 'Neu']]));
}
public function test_unknown_type_and_unregistered_variant_are_rejected(): void
{
try {
$this->registry()->normalize([['type' => 'html', 'v' => 1, 'data' => ['markup' => '<script></script>']]]);
$this->fail('Unbekannte Art wurde angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('blocks.0.type', $exception->errors());
}
try {
$this->registry()->normalize([['type' => 'hero', 'v' => 1, 'variant' => 'gross-und-bunt', 'data' => ['heading' => 'X']]]);
$this->fail('Unbekannte Variante wurde angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('blocks.0.variant', $exception->errors());
}
}
public function test_free_settings_are_rejected(): void
{
$this->expectException(ValidationException::class);
$this->registry()->normalize([
['type' => 'heading', 'v' => 1, 'settings' => ['class' => 'bg-red-500'], 'data' => ['heading' => 'X']],
]);
}
public function test_image_text_requires_an_alternative_text_when_an_image_is_set(): void
{
try {
$this->registry()->normalize([
['type' => 'image_text', 'v' => 2, 'data' => ['body' => '<p>Text</p>'], 'refs' => ['image' => 'cms/bild.jpg']],
]);
$this->fail('Bild ohne Alternativtext wurde angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('blocks.0.data.alt', $exception->errors());
}
$stored = $this->registry()->normalize([
['type' => 'image_text', 'v' => 2, 'data' => ['body' => '<p>Ohne Bild</p>'], 'refs' => []],
]);
$this->assertNull($stored[0]['refs']['image']);
}
public function test_links_reject_script_urls_in_every_widget(): void
{
$cases = [
['type' => 'call_to_action', 'heading' => 'Weiter', 'label' => 'Öffnen', 'url' => 'javascript:alert(1)'],
['type' => 'cards', 'v' => 1, 'data' => ['items' => [['title' => 'A', 'url' => 'javascript:alert(1)']]]],
['type' => 'hero', 'v' => 1, 'data' => ['heading' => 'A', 'cta_label' => 'Los', 'cta_url' => '//fremd.example/x']],
];
foreach ($cases as $case) {
try {
$this->registry()->normalize([$case]);
$this->fail('Unsichere Adresse wurde angenommen: '.$case['type']);
} catch (ValidationException) {
$this->addToAssertionCount(1);
}
}
}
public function test_images_must_come_from_the_public_website_area(): void
{
$this->expectException(ValidationException::class);
$this->registry()->normalize([
['type' => 'hero', 'v' => 1, 'data' => ['heading' => 'A', 'alt' => 'Bild'], 'refs' => ['image' => 'bibliothek/geschuetzt.jpg']],
]);
}
public function test_formatted_text_is_sanitized_when_saved(): void
{
$stored = $this->registry()->normalize([[
'type' => 'image_text',
'v' => 2,
'data' => ['body' => '<p onclick="x()">Hallo <strong>Welt</strong><script>alert(1)</script> <a href="javascript:alert(1)">böse</a> <a href="/praevention">gut</a></p><iframe src="x"></iframe>'],
]]);
$body = $stored[0]['data']['body'];
$this->assertStringNotContainsString('script', $body);
$this->assertStringNotContainsString('onclick', $body);
$this->assertStringNotContainsString('javascript:', $body);
$this->assertStringNotContainsString('iframe', $body);
$this->assertStringContainsString('<strong>Welt</strong>', $body);
$this->assertStringContainsString('href="/praevention"', $body);
}
public function test_legacy_blocks_are_read_as_version_one_envelopes(): void
{
$widget = $this->registry()->upcast(['type' => 'heading', 'heading' => 'Alt', 'intro' => 'Einleitung']);
$this->assertSame([
'id' => null,
'type' => 'heading',
'v' => 1,
'variant' => 'standard',
'settings' => [],
'data' => ['heading' => 'Alt', 'intro' => 'Einleitung'],
'refs' => [],
], $widget);
}
public function test_legacy_image_text_is_upgraded_to_version_two_on_read(): void
{
$legacy = ['type' => 'image_text', 'image' => 'cms/alt.jpg', 'alt' => 'Kinder im Kreis', 'body' => "Erster Absatz & mehr.\n\nZweiter <Absatz>."];
$widget = $this->registry()->upcast($legacy);
$this->assertSame(2, $widget['v']);
$this->assertSame('image_left', $widget['variant']);
$this->assertSame(['image' => 'cms/alt.jpg'], $widget['refs']);
$this->assertSame('Kinder im Kreis', $widget['data']['alt']);
$this->assertNull($widget['data']['title']);
$this->assertSame('<p>Erster Absatz &amp; mehr.</p><p>Zweiter &lt;Absatz&gt;.</p>', $widget['data']['body']);
}
public function test_stored_version_one_envelope_is_upgraded_as_well(): void
{
$widget = $this->registry()->upcast([
'id' => 'abc', 'type' => 'image_text', 'v' => 1, 'variant' => 'standard',
'data' => ['image' => null, 'alt' => 'x', 'body' => 'Nur Text'], 'refs' => [],
]);
$this->assertSame(2, $widget['v']);
$this->assertSame('abc', $widget['id']);
$this->assertSame('image_left', $widget['variant']);
$this->assertSame('<p>Nur Text</p>', $widget['data']['body']);
}
public function test_widgets_from_a_newer_schema_cannot_be_saved(): void
{
$this->expectException(ValidationException::class);
$this->registry()->normalize([['type' => 'heading', 'v' => 99, 'data' => ['heading' => 'Zukunft']]]);
}
public function test_read_skips_unknown_types_without_failing(): void
{
$widgets = $this->registry()->read([
['type' => 'gibt_es_nicht', 'v' => 1],
['type' => 'prose', 'body' => 'Bleibt lesbar'],
]);
$this->assertCount(1, $widgets);
$this->assertSame('prose', $widgets[0]['type']);
}
public function test_ids_are_kept_and_duplicates_get_new_ids(): void
{
$stored = $this->registry()->normalize([
['id' => 'erster', 'type' => 'heading', 'v' => 1, 'data' => ['heading' => 'A']],
['id' => 'erster', 'type' => 'heading', 'v' => 1, 'data' => ['heading' => 'Kopie']],
['type' => 'prose', 'body' => 'Ohne Kennung'],
]);
$this->assertSame('erster', $stored[0]['id']);
$this->assertNotSame('erster', $stored[1]['id']);
$this->assertNotEmpty($stored[2]['id']);
$this->assertNotSame($stored[1]['id'], $stored[2]['id']);
}
public function test_only_declared_fields_are_stored(): void
{
$stored = $this->registry()->normalize([[
'type' => 'cards',
'v' => 1,
'data' => ['items' => [['title' => 'A', 'price' => '99 €', 'url' => '/a']], 'license' => 'alle'],
'refs' => ['offer' => 7],
]]);
$this->assertSame(['items' => [['title' => 'A', 'text' => null, 'url' => '/a', 'image' => null]]], $stored[0]['data']);
$this->assertSame([], $stored[0]['refs']);
}
public function test_rich_text_from_plain_text_escapes_markup(): void
{
$this->assertSame('<p>&lt;b&gt;fett&lt;/b&gt;</p>', RichText::fromPlainText('<b>fett</b>'));
$this->assertSame('', RichText::fromPlainText(" \n "));
}
private function customWidget(string $key): WidgetType
{
return new class($key) extends WidgetType
{
public function __construct(private readonly string $widgetKey) {}
public function key(): string
{
return $this->widgetKey;
}
public function label(): string
{
return 'Teaser';
}
public function description(): string
{
return 'Testwidget';
}
public function variants(): array
{
return ['standard' => 'Standard', 'wide' => 'Breit'];
}
public function dataRules(): array
{
return ['heading' => ['required', 'string', 'max:50']];
}
public function dataFields(): array
{
return [TextInput::make('heading')];
}
public function view(): string
{
return 'widgets.heading';
}
public function summary(array $widget): string
{
return (string) ($widget['data']['heading'] ?? '');
}
};
}
}