Files
laraundfelix/tests/Unit/WidgetRegistryTest.php
T
LarsandClaude Opus 5.5 5548106c31 Verdichte Seitenaufbau und Abschnittsgestaltung im CMS
- Seitenaufbau: Bausteine als Miniaturvorschau in Desktop-Proportion (verkleinert,
  Höhe begrenzt); Abschnittskopf „Abschnitt N“ mit knapper Angabe zu Raster und
  abweichender Gestaltung, vollständig im Titel; Plätze ohne eigenen Kopf, nur
  über Lage und Breite; Aktionen benennen Abschnitt oder Baustein.
- Seitenkopf kompakter; Erläuterungen als aufrufbare Hilfe; kein Rahmen
  „Inhalt der Seite“, keine leeren Abstände ausgeblendeter Teile.
- „Abschnitt gestalten“: knappe Leiste mit „Zum Seitenaufbau“ und Hilfe, keine
  wiederholte Zusammenfassung; Einstellungen in Raster und Breite, Hintergrund,
  Abstände und Trenner; Erklärungen als Hinweis. Rückkehr an den Abschnitt.
- Tests: Gruppen speichern gemeinsam; Texte bewusst angepasst.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:37:14 +01:00

379 lines
16 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\Foundation\Testing\RefreshDatabase;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use Tests\TestCase;
class WidgetRegistryTest extends TestCase
{
use RefreshDatabase;
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', 'topic_card', 'media_card', 'program_card', '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')]);
}
/** Gemeinsamer Layoutvertrag (ADR-38) für jede registrierte Art. */
public function test_every_widget_declares_the_shared_layout_contract(): void
{
foreach ($this->registry()->all() as $key => $type) {
$units = $type->supportedUnits();
$this->assertNotEmpty($units, $key);
$this->assertSame([], array_diff($units, [1, 2, 3, 4]), $key);
$this->assertSame(min($units), $type->minUnits(), $key);
$this->assertTrue($type->supportsUnits($type->preferredUnits()), $key);
$this->assertNotEmpty($type->stages(), $key);
$this->assertNotSame('', $type->narrowBehavior(), $key);
$this->assertSame([], array_diff(array_keys($type->heights()), array_keys(WidgetType::HEIGHTS)), $key);
if ($type->heights() !== []) {
$this->assertArrayHasKey($type->defaultHeight(), $type->heights(), $key);
$this->assertSame($type->heights(), $type->settingOptions()['height'], $key);
}
}
$this->assertSame([3, 4], $this->registry()->get('hero')->supportedUnits());
$this->assertSame(['compact', 'normal', 'large'], array_keys($this->registry()->get('hero')->heights()));
$this->assertSame([1, 2, 3, 4], $this->registry()->get('image_text')->supportedUnits());
$this->assertSame(['compact', 'normal', 'spacious'], array_keys($this->registry()->get('image_text')->heights()));
$this->assertSame(['auto', 'fill'], array_keys($this->registry()->get('call_to_action')->heights()));
$this->assertSame([2, 3, 4], $this->registry()->get('faq')->supportedUnits());
$this->assertSame('3 oder 4', $this->registry()->get('hero')->unitsLabel());
$this->assertSame('1 bis 4', $this->registry()->get('cards')->unitsLabel());
}
public function test_height_is_an_enumerated_setting_with_a_default(): void
{
$widget = $this->registry()->normalize([
['type' => 'hero', 'v' => 2, 'settings' => ['height' => 'large'], 'data' => ['heading' => 'X']],
])[0];
$this->assertSame('large', $widget['settings']['height']);
$this->assertSame('normal', $this->registry()->get('hero')->height(['settings' => []]));
try {
$this->registry()->normalize([['type' => 'hero', 'v' => 2, 'settings' => ['height' => '900px'], 'data' => ['heading' => 'X']]]);
$this->fail('Freie Höhe wurde angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('blocks.0.settings.height', $exception->errors());
}
try {
$this->registry()->normalize([['type' => 'prose', 'v' => 1, 'settings' => ['height' => 'compact'], 'data' => ['body' => 'Text']]]);
$this->fail('Höhe für eine Art ohne Höhenwahl wurde angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('blocks.0.settings.height', $exception->errors());
}
}
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());
// Sichtbar kurzer Name und Inhalt, vollständig (mit Darstellung) im Titel (CMS-Abschluss).
$label = (string) $block->getLabel(['variant' => 'wide', 'data' => ['heading' => 'Neu']]);
$this->assertStringContainsString('title="Teaser · Breit – Neu"', $label);
$this->assertStringContainsString('<span class="luf-baustein-name">Teaser</span>', $label);
$this->assertStringContainsString('<span class="luf-baustein-kurz">Neu</span>', $label);
}
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' => 2, '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']],
]);
}
/**
* Bewusst geändert (zentrale Medienverwaltung): Der Alternativtext gehört zum Medium im Medienmanager. Im Widget ist er
* eine optionale Abweichung und deshalb keine Pflicht mehr; ein früheres CMS-Bild ohne Zuordnung bleibt gültig.
*/
public function test_image_text_takes_the_alternative_text_from_the_medium_and_keeps_legacy_images(): void
{
$stored = $this->registry()->normalize([
['type' => 'image_text', 'v' => 2, 'data' => ['body' => '<p>Text</p>'], 'refs' => ['image' => 'cms/bild.jpg']],
]);
$this->assertSame('cms/bild.jpg', $stored[0]['refs']['image']);
$this->assertNull($stored[0]['data']['alt']);
$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_the_current_version_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(3, $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(3, $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'] ?? '');
}
};
}
}