Files
laraundfelix/tests/Feature/CmsEditorTest.php
T
LarsandClaude Opus 5.5 6152451e2e
CI Feature / test (push) Successful in 34s
Deploy Test / test (push) Successful in 30s
Deploy Test / deploy (push) Successful in 28s
Füge duplizierte Abschnitte direkt hinter dem Original ein.
Filament hängt eine Kopie sonst ans Seitenende; auf langen Seiten war sie dort
schwer zu finden. Gefunden in der Browserprüfung.

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

516 lines
24 KiB
PHP

<?php
namespace Tests\Feature;
use App\Domain\Catalog\PillarService;
use App\Domain\Cms\NavigationItem;
use App\Domain\Cms\Page;
use App\Filament\Resources\NavigationItems\Pages\ManageNavigationItems;
use App\Filament\Resources\Pages\Pages\CreatePage;
use App\Filament\Resources\Pages\Pages\EditPage;
use App\Filament\Resources\Pages\Pages\ListPages;
use App\Filament\Support\WidgetEditor;
use App\Models\User;
use Filament\Actions\Testing\TestAction;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Livewire\Livewire;
use Tests\Support\BuildsCatalog;
use Tests\TestCase;
/**
* Seiteneditor mit Abschnitten und Plätzen. Der Formularzustand ist seit dem Abschnittsraster
* {sections: {uuid: {id, layout, style, slots: {uuid: {widget: {uuid: Builder-Eintrag}}}}}}
* statt einer flachen Bausteinliste; die Prüfungen der ersten Iteration gelten unverändert für die Widgets darin.
*/
class CmsEditorTest extends TestCase
{
use BuildsCatalog;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Filament::setCurrentPanel(Filament::getPanel('verwaltung'));
}
public function test_editor_creates_a_page_with_sections_and_registered_widgets_without_publishing_it(): void
{
$program = $this->composition('Programm Abstand', 'programm');
Livewire::actingAs($this->editor(), 'staff')
->test(CreatePage::class)
->fillForm([
'path' => '/themen-test',
'seo_title' => 'Themenseite',
'sections' => [
$this->sectionState('u4', [
['type' => 'hero', 'data' => ['variant' => 'highlight', 'data' => ['heading' => 'Stark im Alltag', 'text' => 'Einstieg']]],
], ['background' => 'dark', 'divider' => 'accent']),
$this->sectionState('u1_3', [
['type' => 'cards', 'data' => ['variant' => 'compact', 'data' => ['items' => $this->keyed([['title' => 'Prävention', 'url' => '/praevention']])]]],
['type' => 'image_text', 'data' => ['variant' => 'image_right', 'data' => ['title' => 'Worum es geht', 'body' => '<p>Text mit <strong>Betonung</strong></p>'], 'refs' => []]],
], ['width' => 'wide']),
$this->sectionState('u2_2', [
['type' => 'catalog_cards', 'data' => ['variant' => 'standard', 'data' => ['heading' => 'Programme'], 'refs' => ['items' => $this->keyed([['type' => 'composition', 'id' => $program->composition_id]])]]],
null,
]),
],
])
->call('create')
->assertHasNoFormErrors();
$page = Page::query()->where('path', '/themen-test')->firstOrFail();
$revision = $page->latestRevision;
$sections = $revision->sections;
$blocks = $revision->blocks;
$this->assertNull($page->published_revision_id);
$this->assertSame(['u4', 'u1_3', 'u2_2'], array_column($sections, 'layout'));
$this->assertSame('dark', $sections[0]['style']['background']);
$this->assertSame('accent', $sections[0]['style']['divider']);
$this->assertSame('wide', $sections[1]['style']['width']);
$this->assertNull($sections[2]['slots'][1], 'Ein leerer Platz bleibt als Platz erhalten.');
$this->assertSame(['hero', 'cards', 'image_text', 'catalog_cards'], array_column($blocks, 'type'), 'Die Rollback-Spalte enthält alle Widgets in Lesereihenfolge.');
$this->assertSame(['highlight', 'compact', 'image_right', 'standard'], array_column($blocks, 'variant'));
$this->assertSame(2, $blocks[2]['v']);
$this->assertStringContainsString('<strong>Betonung</strong>', $blocks[2]['data']['body']);
$this->assertSame([['title' => 'Prävention', 'text' => null, 'url' => '/praevention', 'image' => null]], $blocks[1]['data']['items']);
$this->assertSame([['type' => 'composition', 'id' => $program->composition_id]], $blocks[3]['refs']['items']);
$this->get('/themen-test')->assertNotFound();
}
public function test_existing_page_opens_in_the_editor_and_saves_without_changing_the_live_page(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$live = $page->published_revision_id;
$before = $this->mainText($this->get('/')->getContent());
$component = Livewire::actingAs($this->editor(), 'staff')
->test(EditPage::class, ['record' => $page->id]);
$this->assertSame(['heading', 'prose', 'cards', 'call_to_action'], $this->widgetTypes($component->get('data.sections')));
$this->assertSame(['u4', 'u4', 'u4', 'u4'], array_column(array_values($component->get('data.sections')), 'layout'), 'Bestand wird als einspaltige Abschnitte geöffnet.');
$component->call('save')->assertHasNoFormErrors();
$page->refresh();
$this->assertSame($live, $page->published_revision_id);
$this->assertNotSame($live, $page->latestRevision->id);
$this->assertSame(['heading', 'prose', 'cards', 'call_to_action'], array_column($page->latestRevision->blocks, 'type'));
$this->assertCount(4, $page->latestRevision->sections);
$this->assertSame($before, $this->mainText($this->get('/')->getContent()));
Livewire::actingAs($this->editor(), 'staff')
->test(EditPage::class, ['record' => $page->id])
->callAction('publish');
$this->assertSame(
trim(file_get_contents(base_path('tests/Fixtures/legacy-pages/home.txt'))),
$this->mainText($this->get('/')->getContent()),
'Nach dem Speichern im neuen Format zeigt die Seite denselben Text.',
);
}
public function test_editor_reorders_and_duplicates_sections(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]);
$state = $component->get('data.sections');
$keys = array_keys($state);
$reordered = [$keys[3] => $state[$keys[3]], $keys[0] => $state[$keys[0]], $keys[1] => $state[$keys[1]], $keys[2] => $state[$keys[2]]];
$reordered[(string) Str::uuid()] = $state[$keys[1]];
$component->set('data.sections', $reordered)->call('save')->assertHasNoFormErrors();
$revision = $page->fresh()->latestRevision;
$this->assertSame(['call_to_action', 'heading', 'prose', 'cards', 'prose'], array_column($revision->blocks, 'type'));
$this->assertCount(5, array_unique(array_column($revision->blocks, 'id')), 'Ein dupliziertes Widget erhält eine eigene Kennung.');
$this->assertCount(5, array_unique(array_column($revision->sections, 'id')), 'Ein duplizierter Abschnitt erhält eine eigene Kennung.');
}
public function test_duplicate_action_places_the_copy_right_after_the_section(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]);
$keys = array_keys($component->get('data.sections'));
$component->callAction(TestAction::make('clone')->schemaComponent('sections')->arguments(['item' => $keys[1]]));
$this->assertSame(['heading', 'prose', 'prose', 'cards', 'call_to_action'], $this->widgetTypes($component->get('data.sections')));
$component->call('save')->assertHasNoFormErrors();
$this->assertSame(['heading', 'prose', 'prose', 'cards', 'call_to_action'], array_column($page->fresh()->latestRevision->blocks, 'type'));
}
public function test_layout_change_keeps_widgets_and_rejects_layouts_with_too_few_slots(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]);
$state = $component->get('data.sections');
$keys = array_keys($state);
// Raster wechseln: fehlende Plätze entstehen, das vorhandene Widget bleibt im ersten Platz.
$component->set("data.sections.{$keys[0]}.layout", 'u1_1_1_1');
$slots = $component->get("data.sections.{$keys[0]}.slots");
$this->assertCount(4, $slots);
$this->assertSame(['heading'], $this->widgetTypes([['slots' => $slots]]));
// Zweites Widget in Platz 2 setzen und auf zwei Plätze wechseln: leere Plätze entfallen, Widgets bleiben.
$slotKeys = array_keys($slots);
$secondWidget = $state[$keys[1]]['slots'][array_key_first($state[$keys[1]]['slots'])]['widget'];
$component->set("data.sections.{$keys[0]}.slots.{$slotKeys[1]}.widget", $secondWidget);
$component->set("data.sections.{$keys[0]}.layout", 'u2_2');
$this->assertCount(2, $component->get("data.sections.{$keys[0]}.slots"));
$this->assertSame(['heading', 'prose'], $this->widgetTypes([['slots' => $component->get("data.sections.{$keys[0]}.slots")]]));
// Ein Raster mit nur einem Platz ist gesperrt, solange zwei Widgets eingesetzt sind; kein Widget geht verloren.
$component->set("data.sections.{$keys[0]}.layout", 'u4');
$this->assertCount(2, $component->get("data.sections.{$keys[0]}.slots"));
$component->call('save')->assertHasErrors(["data.sections.{$keys[0]}.layout"]);
$component->set("data.sections.{$keys[0]}.layout", 'u2_2');
$remaining = $component->get('data.sections');
unset($remaining[$keys[1]]);
$component->set('data.sections', $remaining)->call('save')->assertHasNoFormErrors();
$sections = $page->fresh()->latestRevision->sections;
$this->assertCount(3, $sections);
$this->assertSame('u2_2', $sections[0]['layout']);
$this->assertSame(['heading', 'prose'], array_column($sections[0]['slots'], 'type'));
}
public function test_widget_too_wide_for_its_slot_is_reported_at_the_section(): void
{
$component = Livewire::actingAs($this->editor(), 'staff')
->test(CreatePage::class)
->fillForm([
'path' => '/raster-pruefung',
'sections' => [
$this->sectionState('u1_3', [
['type' => 'hero', 'data' => ['variant' => 'standard', 'data' => ['heading' => 'Zu schmal']]],
null,
], ['background' => 'accent', 'spacing' => 'large', 'divider' => 'line']),
],
])
->call('create')
->assertNotified('Nicht gespeichert');
$key = array_key_first($component->get('data.sections'));
$component->assertHasErrors(["data.sections.$key.slots"]);
$this->assertNull(Page::query()->where('path', '/raster-pruefung')->first());
}
public function test_unsafe_link_is_reported_at_the_section_and_nothing_is_saved(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$revisions = $page->revisions()->count();
$component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]);
$sectionKey = array_keys($component->get('data.sections'))[3];
$slotKey = array_key_first($component->get("data.sections.$sectionKey.slots"));
$widgetKey = array_key_first($component->get("data.sections.$sectionKey.slots.$slotKey.widget"));
$component->set("data.sections.$sectionKey.slots.$slotKey.widget.$widgetKey.data.data.url", 'javascript:alert(1)')
->call('save')
->assertHasErrors([
"data.sections.$sectionKey.slots.$slotKey.widget.$widgetKey.data.data.url",
"data.sections.$sectionKey.slots",
])
->assertNotified('Nicht gespeichert');
$this->assertSame($revisions, $page->revisions()->count());
}
public function test_errors_found_only_by_the_registry_are_announced_with_the_section(): void
{
Storage::fake('media_public');
Storage::fake('cms_incoming');
Storage::disk('media_public')->put('cms/bild.jpg', 'bild');
$page = Page::query()->where('path', '/')->firstOrFail();
$revisions = $page->revisions()->count();
$component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]);
$state = $component->get('data.sections');
$state[(string) Str::uuid()] = $this->sectionState('u4', [
['type' => 'hero', 'data' => ['variant' => 'standard', 'data' => ['heading' => 'Mit Bild'], 'refs' => ['image' => 'cms/bild.jpg']]],
]);
$component->set('data.sections', $state)
->call('save')
->assertNotified('Nicht gespeichert');
$this->assertSame($revisions, $page->revisions()->count());
}
public function test_section_background_image_is_saved_and_published_from_the_public_area(): void
{
Storage::fake('media_public');
Storage::fake('cms_incoming');
Storage::disk('media_public')->put('cms/flaeche.jpg', 'bild');
Livewire::actingAs($this->editor(), 'staff')
->test(CreatePage::class)
->fillForm([
'path' => '/flaechen',
'sections' => [
$this->sectionState('u2_2', [
['type' => 'heading', 'data' => ['variant' => 'standard', 'data' => ['heading' => 'Auf Bild']]],
['type' => 'prose', 'data' => ['variant' => 'standard', 'data' => ['body' => 'Text']]],
], ['background' => 'image', 'image' => 'cms/flaeche.jpg', 'focus' => 'top', 'overlay' => 'dark']),
],
])
->call('create')
->assertHasNoFormErrors();
$style = Page::query()->where('path', '/flaechen')->firstOrFail()->latestRevision->sections[0]['style'];
$this->assertSame(['background' => 'image', 'image' => 'cms/flaeche.jpg', 'focus' => 'top', 'overlay' => 'dark'], array_intersect_key($style, array_flip(['background', 'image', 'focus', 'overlay'])));
}
public function test_page_can_be_duplicated_as_an_unpublished_draft_without_changing_the_source(): void
{
$source = Page::query()->where('path', '/praevention')->firstOrFail();
$sourceRevision = $source->latestRevision->id;
$editor = $this->editor();
Livewire::actingAs($editor, 'staff')
->test(ListPages::class)
->callAction(TestAction::make('duplicate')->table($source), ['path' => '/praevention'])
->assertHasActionErrors(['path']);
Livewire::actingAs($editor, 'staff')
->test(ListPages::class)
->callAction(TestAction::make('duplicate')->table($source), ['path' => '/neue-landingpage'])
->assertHasNoActionErrors();
$copy = Page::query()->where('path', '/neue-landingpage')->firstOrFail();
$this->assertNull($copy->published_revision_id);
$this->assertSame(
array_column($source->latestRevision->widgets(), 'type'),
array_column($copy->latestRevision->widgets(), 'type'),
);
$this->assertSame($sourceRevision, $source->fresh()->latestRevision->id, 'Die Vorlage bleibt unverändert.');
}
public function test_new_page_keeps_the_selected_pillars(): void
{
$pillar = app(PillarService::class)->create('Grenzen');
Livewire::actingAs($this->editor(), 'staff')
->test(CreatePage::class)
->fillForm(['path' => '/grenzen-thema', 'pillars' => [$pillar->id], 'sections' => []])
->call('create')
->assertHasNoFormErrors();
$this->assertSame([$pillar->id], Page::query()->where('path', '/grenzen-thema')->firstOrFail()->pillars()->pluck('pillars.id')->all());
}
public function test_duplicated_section_keeps_its_new_id_across_saves(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]);
$state = $component->get('data.sections');
$state[(string) Str::uuid()] = $state[array_key_first($state)];
$component->set('data.sections', $state)->call('save')->assertHasNoFormErrors();
$first = array_column($page->fresh()->latestRevision->blocks, 'id');
$firstSections = array_column($page->fresh()->latestRevision->sections, 'id');
$component->call('save')->assertHasNoFormErrors();
$this->assertCount(5, array_unique($first));
$this->assertSame($first, array_column($page->fresh()->latestRevision->blocks, 'id'));
$this->assertSame($firstSections, array_column($page->fresh()->latestRevision->sections, 'id'));
}
public function test_invalid_or_taken_paths_are_shown_at_the_path_field(): void
{
Livewire::actingAs($this->editor(), 'staff')
->test(CreatePage::class)
->fillForm(['path' => '/praevention', 'sections' => []])
->call('create')
->assertHasErrors(['data.path']);
Livewire::actingAs($this->editor(), 'staff')
->test(CreatePage::class)
->fillForm(['path' => 'C:/Program Files/x', 'sections' => []])
->call('create')
->assertHasErrors(['data.path']);
$this->assertSame(1, Page::query()->where('path', '/praevention')->count());
}
public function test_block_preview_uses_the_public_widget_view_with_unsaved_state(): void
{
$html = WidgetEditor::renderPreview('image_text', [
'variant' => 'image_right',
'data' => [
'title' => 'Ungespeichert',
'body' => ['type' => 'doc', 'content' => [['type' => 'paragraph', 'content' => [['type' => 'text', 'text' => 'Vorschautext']]]]],
],
'refs' => ['image' => null, '_upload' => []],
]);
$this->assertStringContainsString('image-text image-text-right', $html);
$this->assertStringContainsString('<h2>Ungespeichert</h2>', $html);
$this->assertStringContainsString('Vorschautext', $html);
$cards = WidgetEditor::renderPreview('cards', [
'variant' => 'standard',
'data' => ['items' => [(string) Str::uuid() => ['title' => 'Karte A'], (string) Str::uuid() => ['title' => 'Karte B']]],
]);
$this->assertStringContainsString('Karte A', $cards);
$this->assertStringContainsString('Karte B', $cards);
}
public function test_editor_offers_every_registered_widget_layouts_and_section_design(): void
{
$page = Page::query()->where('path', '/')->firstOrFail();
$component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]);
$first = array_key_first($component->get('data.sections'));
// Die Widget-Auswahl erscheint an jedem freien Platz.
$component->set("data.sections.$first.layout", 'u2_2')
->assertSee('Einstieg (Hero)')
->assertSee('Programm- und Modulkarten')
->assertSee('Titel und Beschreibung kommen automatisch aus den Fachdaten')
->assertSee('Braucht einen Platz ab 2 Rastereinheiten')
->assertSee('Gestaltung des Abschnitts')
->assertSee('1 + 2 + 1')
->assertSee('Widget einsetzen')
->assertSee('Entwurf speichern');
}
public function test_preview_with_device_widths_is_only_available_to_staff(): void
{
$revision = Page::query()->where('path', '/')->firstOrFail()->latestRevision;
$this->get(route('pages.preview.devices', $revision))->assertRedirect();
$this->actingAs(User::factory()->create())->get(route('pages.preview', $revision))->assertRedirect();
$this->actingAs(User::factory()->create(), 'staff')->get(route('pages.preview', $revision))->assertForbidden();
auth('web')->logout();
$this->actingAs($this->editor(), 'staff')
->get(route('pages.preview.devices', $revision))
->assertOk()
->assertSee('data-width="390"', false)
->assertSee('data-width="768"', false)
->assertSee('data-width="1440"', false)
->assertSee(route('pages.preview', $revision), false);
$this->actingAs($this->editor(), 'staff')
->get(route('pages.preview', $revision))
->assertOk()
->assertSee('Vorschau einer unveröffentlichten Revision')
->assertSee('<meta name="robots" content="noindex, nofollow">', false)
->assertSee('class="site-header"', false)
->assertSee('class="site-footer scope-dark"', false);
}
public function test_navigation_items_can_be_edited_hidden_reordered_and_removed(): void
{
$editor = $this->editor();
$start = NavigationItem::query()->where('label', 'Start')->firstOrFail();
$about = NavigationItem::query()->where('label', 'Über das Projekt')->firstOrFail();
Livewire::actingAs($editor, 'staff')
->test(ManageNavigationItems::class)
->assertCanSeeTableRecords([$start, $about])
->callAction(TestAction::make('edit')->table($about), ['label' => 'Über uns'])
->assertHasNoFormErrors()
->callAction(TestAction::make('toggleVisibility')->table($start));
$this->assertSame('Über uns', $about->fresh()->label);
$this->assertFalse($start->fresh()->is_visible);
$this->get('/praevention')->assertSee('Über uns')->assertDontSee('>Start<', false);
$order = NavigationItem::query()->orderByDesc('sort_order')->pluck('id')->map(fn ($id) => (string) $id)->all();
Livewire::actingAs($editor, 'staff')->test(ManageNavigationItems::class)->call('reorderTable', $order);
$this->assertSame((int) $order[0], NavigationItem::query()->orderBy('sort_order')->first()->id);
Livewire::actingAs($editor, 'staff')
->test(ManageNavigationItems::class)
->callAction(TestAction::make('delete')->table($about));
$this->assertNull($about->fresh());
$this->assertNotNull(Page::query()->where('path', '/ueber')->first(), 'Die Seite bleibt bestehen.');
}
public function test_navigation_rejects_script_addresses(): void
{
Livewire::actingAs($this->editor(), 'staff')
->test(ManageNavigationItems::class)
->callAction('create', ['label' => 'Böse', 'placement' => 'header', 'url' => 'javascript:alert(1)', 'sort_order' => 9, 'is_visible' => true])
->assertHasFormErrors(['url']);
NavigationItem::query()->create(['label' => 'Alt', 'url' => 'javascript:alert(1)', 'placement' => 'footer', 'sort_order' => 99]);
$this->get('/praevention')->assertDontSee('javascript:alert(1)', false);
}
private function editor(): User
{
$editor = User::factory()->redakteur()->create();
$editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP');
return $editor;
}
/**
* Formularzustand eines Abschnitts; null steht für einen leeren Platz.
*
* @param list<array<string, mixed>|null> $widgets
* @param array<string, mixed> $style
* @return array<string, mixed>
*/
private function sectionState(string $layout, array $widgets, array $style = []): array
{
$slots = [];
foreach ($widgets as $widget) {
$slots[(string) Str::uuid()] = ['widget' => $widget === null ? [] : $this->keyed([$widget])];
}
return ['id' => null, 'layout' => $layout, 'style' => $style, 'slots' => $slots];
}
/**
* @param array<int|string, mixed> $sections
* @return list<string>
*/
private function widgetTypes(array $sections): array
{
$types = [];
foreach ($sections as $section) {
foreach ($section['slots'] ?? [] as $slot) {
foreach ($slot['widget'] ?? [] as $item) {
$types[] = $item['type'];
}
}
}
return $types;
}
/**
* @param list<array<string, mixed>> $items
* @return array<string, array<string, mixed>>
*/
private function keyed(array $items): array
{
$keyed = [];
foreach ($items as $item) {
$keyed[(string) Str::uuid()] = $item;
}
return $keyed;
}
private function mainText(string $html): string
{
preg_match('#<main[^>]*>(.*)</main>#s', $html, $match);
$text = html_entity_decode(strip_tags(str_replace('<', ' <', $match[1] ?? '')), ENT_QUOTES | ENT_HTML5, 'UTF-8');
return trim(preg_replace('/\s+/u', ' ', $text));
}
}