Files
laraundfelix/tests/Feature/CmsWebsiteMediaTest.php
T
LarsandClaude Opus 5.5 053a8d4648
CI Feature / test (push) Successful in 48s
Deploy Test / test (push) Successful in 44s
Deploy Test / deploy (push) Successful in 37s
Stelle alle CMS-Bilder auf die zentrale Medienverwaltung um.
- Einstieg, Bild und Text, redaktionelle Karten, Premium-Karten und Abschnittshintergrund speichern die
  Kennung des Mediums (Bildschlüssel image) und lesen über WebsiteMedia; öffentlich nur mit Website-Freigabe,
  in der Redaktionsvorschau sonst das Vorschaubild mit Hinweis.
- Gemeinsame Felder: Medienpicker mit Vorschaubild und Status, Upload direkt über WebsiteIntake, Anzeige des
  gewählten Mediums mit Verweis auf den Medienmanager. Die CMS-eigene Bildauswahl entfällt.
- Frühere CMS-Bilder übernimmt ein Warteschlangen-Job (dedupliziert, nichts gelöscht); website_media_aliases
  ordnet frühere Pfade zu, wirksam erst nach der ersten Website-Freigabe; /medien/cms/ folgt danach der Freigabe.
- Medienansicht nennt die Website-Seiten, die ein Bild verwenden.
- Bewusst geändert: Der Alternativtext gehört zum Medium und ist im Widget nur noch eine optionale Abweichung;
  die Tests zur Alt-Text-Pflicht prüfen jetzt Übernahme und andere Registry-Fehler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:32:29 +01:00

276 lines
14 KiB
PHP

<?php
namespace Tests\Feature;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentService;
use App\Domain\Cms\Page;
use App\Domain\Cms\PageRevision;
use App\Domain\Cms\PageService;
use App\Domain\Cms\WebsiteImageUsage;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Media\WebsiteIntake;
use App\Domain\Media\WebsiteMediaAlias;
use App\Domain\Media\WebsiteRelease;
use App\Filament\Resources\Pages\Pages\EditPage;
use App\Jobs\ImportCmsImages;
use App\Models\User;
use Filament\Actions\Testing\TestAction;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Livewire\Livewire;
use Tests\TestCase;
/**
* CMS-Bilder aus dem zentralen Medienmanager (docs/architektur/medienzugriff-fuer-komponenten.md):
* Auswahl per Kennung, öffentliche Ausgabe nur mit Website-Freigabe, Übernahme früherer CMS-Bilder.
*/
class CmsWebsiteMediaTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Storage::fake('cms_incoming');
Storage::fake('media_derived');
Storage::fake('media_public');
Storage::fake('media_originals');
Filament::setCurrentPanel(Filament::getPanel('verwaltung'));
}
public function test_a_released_medium_is_shown_in_every_widget_through_the_website_route(): void
{
$medium = $this->releasedImage('Lara im Park', 'Lara sitzt auf einer Parkbank');
$url = route('website.media', $medium);
$revision = $this->publish('/medien-ueberall', [
['layout' => 'u4', 'style' => ['background' => 'image', 'image' => $medium->id, 'overlay' => 'light'], 'slots' => [
['type' => 'hero', 'v' => 2, 'variant' => 'photo_split', 'data' => ['heading' => 'Einstieg'], 'refs' => ['image' => $medium->id]],
]],
['layout' => 'u2_2', 'style' => [], 'slots' => [
['type' => 'image_text', 'v' => 3, 'variant' => 'image_left', 'data' => ['title' => 'Bild und Text', 'body' => '<p>Text</p>', 'alt' => 'Eigene Beschreibung'], 'refs' => ['image' => $medium->id]],
['type' => 'cards', 'v' => 1, 'data' => ['items' => [['title' => 'Karte', 'image' => $medium->id]]]],
]],
]);
$this->assertSame($medium->id, $revision->sections[0]['slots'][0]['refs']['image'], 'Gespeichert wird die Kennung, keine Kopie.');
$this->assertSame($medium->id, $revision->sections[0]['style']['image']);
$main = $this->main($this->get('/medien-ueberall')->assertOk()->getContent());
$this->assertSame(4, substr_count($main, 'src="'.$url.'"'), 'Hintergrund, Einstieg, Bild und Text, Karte verwenden dasselbe Medium.');
$this->assertStringContainsString('alt="Lara sitzt auf einer Parkbank"', $main, 'Alternativtext des Mediums.');
$this->assertStringContainsString('alt="Eigene Beschreibung"', $main, 'Abweichender Alternativtext im Widget.');
$this->assertStringNotContainsString('/redaktion/', $main);
$this->assertStringNotContainsString('/medien/cms/', $main);
$this->assertSame([['path' => '/medien-ueberall', 'published' => true, 'draft' => false]], app(WebsiteImageUsage::class)->pages($medium), 'Der Medienmanager zeigt die Verwendung auf Website-Seiten.');
}
public function test_an_unreleased_medium_is_only_shown_in_the_preview_with_a_notice(): void
{
$medium = $this->unreleasedImage('Noch nicht freigegeben');
$revision = $this->publish('/nicht-freigegeben', [
['layout' => 'u4', 'style' => [], 'slots' => [
['type' => 'image_text', 'v' => 3, 'variant' => 'image_left', 'data' => ['title' => 'Mit Bild', 'body' => '<p>Text bleibt sichtbar.</p>'], 'refs' => ['image' => $medium->id]],
]],
]);
$main = $this->main($this->get('/nicht-freigegeben')->assertOk()->getContent());
$this->assertStringContainsString('Text bleibt sichtbar.', $main, 'Nur das Bild entfällt, nicht das Widget.');
$this->assertStringNotContainsString('<img', $main);
$this->assertStringContainsString('lf-bt--without-image', $main);
$preview = $this->actingAs(User::factory()->redakteur()->create(), 'staff')->get(route('pages.preview', $revision))->assertOk()->getContent();
$this->assertStringContainsString('src="'.route('editorial.card', ['kind' => 'element', 'subject' => $medium->id]).'"', $preview);
$this->assertStringContainsString('Das gewählte Bild „Noch nicht freigegeben“ erscheint öffentlich nicht: Nicht für die Website freigegeben.', $preview);
}
public function test_withdrawing_the_release_removes_the_image_from_pages_and_closes_the_former_address(): void
{
Storage::disk('media_public')->put('cms/altbild-abc123.jpg', $this->jpeg(1200, 600));
$this->publish('/altbild', [
['layout' => 'u4', 'style' => [], 'slots' => [
['type' => 'hero', 'v' => 2, 'variant' => 'photo_split', 'data' => ['heading' => 'Früher'], 'refs' => ['image' => 'cms/altbild-abc123.jpg']],
]],
]);
(new ImportCmsImages)->handle(app(WebsiteIntake::class));
$medium = WebsiteMediaAlias::query()->where('legacy_path', 'cms/altbild-abc123.jpg')->firstOrFail()->element;
$this->assertNotNull($medium->website_released_at);
$this->refreshScoped();
$this->get('/altbild')->assertSee('src="'.route('website.media', $medium).'"', false)->assertDontSee('/medien/cms/altbild', false);
$this->get('/medien/cms/altbild-abc123.jpg')->assertOk();
app(WebsiteRelease::class)->withdraw($medium);
$this->refreshScoped();
$this->assertStringNotContainsString('<img', $this->main($this->get('/altbild')->assertOk()->getContent()));
$this->get('/medien/cms/altbild-abc123.jpg')->assertNotFound();
$this->get(route('website.media', $medium))->assertNotFound();
Storage::disk('media_public')->assertExists('cms/altbild-abc123.jpg');
}
public function test_former_cms_images_are_imported_once_deduplicated_and_without_deleting_files(): void
{
$same = $this->jpeg(800, 400);
Storage::disk('media_public')->put('cms/platzhalter-karte-1-aaaaaa.jpg', $same);
Storage::disk('media_public')->put('cms/platzhalter-karte-1-bbbbbb.jpg', $same);
Storage::disk('media_public')->put('cms/markenbuehne-cccccc.png', $this->jpeg(900, 300));
Storage::disk('media_public')->put('cms/notiz.txt', 'kein Bild');
(new ImportCmsImages)->handle(app(WebsiteIntake::class));
(new ImportCmsImages)->handle(app(WebsiteIntake::class));
$this->assertSame(3, WebsiteMediaAlias::query()->count());
$this->assertSame(2, ContentElement::query()->where('output_class', 'bild')->count(), 'Bytegleiche Dateien werden ein Medium.');
$this->assertSame(['Markenbuehne', 'Platzhalter Karte 1'], ContentElement::query()->orderBy('working_title')->pluck('working_title')->all());
$this->assertSame(
WebsiteMediaAlias::query()->where('legacy_path', 'cms/platzhalter-karte-1-aaaaaa.jpg')->value('content_element_id'),
WebsiteMediaAlias::query()->where('legacy_path', 'cms/platzhalter-karte-1-bbbbbb.jpg')->value('content_element_id'),
);
foreach (['cms/platzhalter-karte-1-aaaaaa.jpg', 'cms/platzhalter-karte-1-bbbbbb.jpg', 'cms/markenbuehne-cccccc.png'] as $path) {
Storage::disk('media_public')->assertExists($path);
}
$this->assertTrue(ContentElement::query()->get()->every(fn (ContentElement $element): bool => $element->website_released_at !== null));
}
public function test_an_alias_takes_effect_only_after_the_medium_was_released(): void
{
Storage::disk('media_public')->put('cms/kaputt-dddddd.jpg', 'keine Bilddaten');
$this->publish('/kaputt', [
['layout' => 'u4', 'style' => [], 'slots' => [
['type' => 'hero', 'v' => 2, 'variant' => 'photo_split', 'data' => ['heading' => 'Bild bleibt'], 'refs' => ['image' => 'cms/kaputt-dddddd.jpg']],
]],
]);
(new ImportCmsImages)->handle(app(WebsiteIntake::class));
$this->refreshScoped();
$this->assertNotNull(WebsiteMediaAlias::query()->where('legacy_path', 'cms/kaputt-dddddd.jpg')->first());
$this->get('/kaputt')->assertSee('/medien/cms/kaputt-dddddd.jpg', false);
}
public function test_saving_converts_an_imported_path_to_the_medium_and_rejects_other_media(): void
{
Storage::disk('media_public')->put('cms/umzug-eeeeee.jpg', $this->jpeg(1000, 500));
(new ImportCmsImages)->handle(app(WebsiteIntake::class));
$medium = WebsiteMediaAlias::query()->firstOrFail()->element;
$revision = $this->publish('/umzug', [
['layout' => 'u4', 'style' => [], 'slots' => [
['type' => 'hero', 'v' => 2, 'variant' => 'photo_split', 'data' => ['heading' => 'Umzug'], 'refs' => ['image' => 'cms/umzug-eeeeee.jpg']],
]],
]);
$this->assertSame($medium->id, $revision->sections[0]['slots'][0]['refs']['image']);
$film = app(ContentService::class)->createElement('film', 'film', 'Film');
try {
app(PageService::class)->saveRevision(Page::query()->create(['path' => '/film-als-bild']), [
['layout' => 'u4', 'style' => [], 'slots' => [['type' => 'hero', 'v' => 2, 'data' => ['heading' => 'X'], 'refs' => ['image' => $film->id]]]],
], null, null, null);
$this->fail('Ein Film wurde als Bild angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('sections.0.slots.0.refs.image', $exception->errors());
}
}
public function test_an_image_uploaded_in_the_widget_dialog_becomes_a_medium_and_is_selected(): void
{
$editor = User::factory()->redakteur()->create();
$editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP');
$page = Page::query()->create(['path' => '/upload']);
app(PageService::class)->saveRevision($page, [
['layout' => 'u4', 'style' => [], 'slots' => [['type' => 'hero', 'v' => 2, 'variant' => 'photo_split', 'data' => ['heading' => 'Upload'], 'refs' => []]]],
], null, null, null);
$component = Livewire::actingAs($editor, 'staff')->test(EditPage::class, ['record' => $page->id]);
$sectionKey = array_key_first($component->get('data.sections'));
$slotKey = array_key_first($component->get("data.sections.$sectionKey.slots"));
$itemKey = array_key_first($component->get("data.sections.$sectionKey.slots.$slotKey.widget"));
$component->mountAction(TestAction::make('edit')->schemaComponent("sections.$sectionKey.slots.$slotKey.widget")->arguments(['item' => $itemKey]))
->fillForm(['refs._upload' => UploadedFile::fake()->image('lara-im-park.jpg', 1600, 900)])
->callMountedAction()
->assertHasNoErrors();
$medium = ContentElement::query()->where('output_class', 'bild')->latest('id')->firstOrFail();
$this->assertSame('Lara Im Park', $medium->display_title);
$this->assertNotNull($medium->website_released_at, 'Neue Bilder werden nach der Verarbeitung für die Website freigegeben.');
$this->assertSame($medium->id, (int) $component->get("data.sections.$sectionKey.slots.$slotKey.widget.$itemKey.data.refs.image"));
$component->call('save')->assertHasNoFormErrors();
$this->assertSame($medium->id, $page->refresh()->latestRevision->sections[0]['slots'][0]['refs']['image']);
}
public function test_the_picker_lists_website_images_with_their_release_state(): void
{
$released = $this->releasedImage('Freigegeben', null);
$unreleased = $this->unreleasedImage('Unfreigegeben');
app(ContentService::class)->createElement('film', 'film', 'Film taucht nicht auf');
$options = app(WebsiteImage::class)->options();
$this->assertSame([$unreleased->id, $released->id], array_keys($options));
$this->assertStringContainsString('Website: freigegeben', $options[$released->id]);
$this->assertStringContainsString('Website: nicht freigegeben', $options[$unreleased->id]);
$this->assertStringContainsString(route('editorial.card', ['kind' => 'element', 'subject' => $released->id]), $options[$released->id]);
}
private function releasedImage(string $title, ?string $alt): ContentElement
{
$path = 'cms/'.Str::slug($title).'.jpg';
Storage::disk('cms_incoming')->put($path, $this->jpeg(1600, 800));
return app(WebsiteIntake::class)->acceptImage($path, $title, 'Foto: Lara und Felix', $alt)->refresh();
}
private function unreleasedImage(string $title): ContentElement
{
$element = app(ContentService::class)->createElement('bild', 'bild', $title);
$element->forceFill(['thumbnail_path' => 'vorschau/element-'.$element->id.'.jpg'])->save();
Storage::disk('media_derived')->put($element->thumbnail_path, $this->jpeg(640, 320));
return $element->refresh();
}
/**
* @param list<array<string, mixed>> $sections
*/
private function publish(string $path, array $sections): PageRevision
{
$page = Page::query()->firstOrCreate(['path' => $path]);
$service = app(PageService::class);
$revision = $service->saveRevision($page, $sections, null, null, null);
$service->publish($page, $revision);
return $revision;
}
private function refreshScoped(): void
{
$this->app->forgetScopedInstances();
}
private function main(string $html): string
{
preg_match('#<main[^>]*>(.*)</main>#s', $html, $match);
return $match[1] ?? '';
}
private function jpeg(int $width, int $height): string
{
$image = imagecreatetruecolor($width, $height);
imagefill($image, 0, 0, imagecolorallocate($image, 200, 120, 40));
ob_start();
imagejpeg($image);
return (string) ob_get_clean();
}
}