Files
laraundfelix/tests/Unit/WidgetRegistryTest.php
LarsandClaude Opus 5.5 480d55989b
CI Feature / test (push) Failing after 20s
Führe Abschnitte mit Raster, gemeinsames Designsystem und globales Website-Gerüst ein.
- Seite → Abschnitte → Plätze → Widgets: sechs Raster mit höchstens vier Einheiten,
  Hintergrund, Breite, Abstand und Trenner als Aufzählungswerte; je Platz ein Widget
  aus dem bestehenden Register. Neue Spalte page_revisions.sections (ergänzend);
  blocks erhält weiterhin alle Widgets in Lesereihenfolge als Rollback-Fassung.
- Widgets erhalten Mindest- und Vorzugsbreite; Darstellung über Container-Abfragen.
- Editor: Abschnitts-Repeater mit grafischer Rasterauswahl, Plätzen im Rasterverhältnis,
  breiter Arbeitsfläche, kompakten Vorschauen ohne Bildlaufleiste, Meldungen mit
  Abschnitt und Platz; Rasterwechsel entfernt nie ein Widget. Seite duplizieren.
- Designsystem: Marken- und Bedeutungs-Tokens (vorläufig), gemeinsame Grundkomponenten,
  Nunito/Source Sans 3 lokal; Mitgliederbereich nutzt dieselben Tokens und die Wortmarke.
- Kopfzeile, mobile Navigation, Untermenü (parent_id, ergänzend), Fußbereichsgruppen,
  vorbereiteter Warenkorbzugang (abgeschaltet). Öffentliche Seiten gleich für alle Besucher.
- cms:revert-published als Wiederherstellungsweg vor einem Code-Rollback.

Die Editor-Tests der ersten Iteration sind bewusst auf den neuen Formularzustand
(sections statt blocks) umgestellt; ihre Prüfungen gelten unverändert für die Widgets.
Der Vorschautest erwartet keine anmeldeabhängige Kopfzeile mehr (ADR-32).

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

333 lines
13 KiB
PHP
Raw Permalink 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_every_widget_declares_a_minimum_width_within_four_units(): void
{
foreach ($this->registry()->all() as $key => $type) {
$this->assertGreaterThanOrEqual(1, $type->minUnits(), $key);
$this->assertLessThanOrEqual($type->preferredUnits(), $type->minUnits(), $key);
$this->assertLessThanOrEqual(4, $type->preferredUnits(), $key);
$this->assertNotEmpty($type->stages(), $key);
}
$this->assertSame(2, $this->registry()->get('hero')->minUnits());
$this->assertSame(2, $this->registry()->get('image_text')->minUnits());
$this->assertSame(1, $this->registry()->get('catalog_cards')->minUnits());
}
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'] ?? '');
}
};
}
}