Files
laraundfelix/app/Filament/Support/MediumForm.php
T
LarsandClaude Sonnet 5.5 c57a506f85 Biete Tabellen und Bilder im gemeinsamen Texteditor an und setze sie in Ansicht und PDF
Tabellen und Bilder gehören zur festen Auswahl von FormattedText. Ein Bild
ist ein Verweis auf eine freigegebene Bildfassung und kommt per Picker aus
dem Medienbestand; der Stand schreibt die Bildfassung mit fest, die Rechte
entscheidet DecideAccess. Der PDF-Satz (PdfFlow) ist für Übung und kommende
Dokumente gemeinsam; PdfDocument kann zusätzlich Bilder, Flächen, Verweise
und Lesezeichen, Belege bleiben byte-gleich.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 11:31:03 +01:00

297 lines
11 KiB
PHP

<?php
namespace App\Filament\Support;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\EditorialVocabulary;
use App\Domain\Catalog\EmbeddedImages;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\IdentityProfile;
use App\Domain\Media\PresentationFile;
use App\Jobs\DeriveThumbnail;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Illuminate\Support\Facades\Storage;
class MediumForm
{
/**
* @return list<FileUpload|Select|Textarea|TextInput>
*/
public static function fields(bool $creating, ?ContentElement $element = null): array
{
$fields = [
TextInput::make('working_title')->label('Titel')->required(),
];
if ($creating) {
$fields[] = Select::make('editorial_content_kind_id')
->label('Fachliche Materialart')
->options(fn (): array => app(EditorialVocabulary::class)->kindOptions('medium'))
->required()
->helperText('Die redaktionelle Einordnung, zum Beispiel Merkblatt. Sie steht in der Medienliste und lässt sich dort filtern. Die technische Art wählst du darunter.');
$fields[] = Select::make('shape')->label('Technische Art')->options([
'film' => 'Film',
'audio' => 'Hörstück',
'bild' => 'Bild',
'document' => 'Dokument',
'text' => 'Text',
])->required()->live();
$fields[] = RichField::make('body', 'Text', live: false)
->visible(fn ($get): bool => $get('shape') === 'text')
->required(fn ($get): bool => $get('shape') === 'text');
$fields[] = self::fileField()
->visible(fn ($get): bool => filled($get('shape')) && $get('shape') !== 'text')
->required(fn ($get): bool => filled($get('shape')) && $get('shape') !== 'text');
$fields[] = Checkbox::make('without_version')
->label('Eigenständiges Präsentationsmedium')
->helperText('Bild, Film oder Hörstück ohne fachliche Inhaltsfassung, zum Beispiel ein Trailer, der ungeschützt auf der Website laufen soll. Der Film muss dafür MP4 (H.264) oder WebM sein. Er wird nicht lizenziert und erst nach „Für die Website freigeben“ öffentlich.')
->visible(fn ($get): bool => in_array($get('shape'), ['film', 'audio', 'bild'], true));
} elseif ($element?->output_class === 'text') {
$fields[] = RichField::make('body', 'Text', live: false)->required();
}
return [
...$fields,
RichField::make('description', 'Beschreibung', live: false)
->helperText('Gilt für das Medium, nicht nur für diese eine Stelle.'),
Textarea::make('usage_note')->label('Hinweise für den Einsatz')->rows(3),
Textarea::make('license_note')->label('Interner Lizenzvermerk')->rows(3)
->helperText('Nur in der Verwaltung. Nicht in der Bibliothek und nicht auf der Website.'),
TextInput::make('thumbnail_alt')->label('Alternativtext zum Vorschaubild'),
self::thumbnailField(),
];
}
public static function fileField(): FileUpload
{
return FileUpload::make('incoming')
->label('Datei')
->disk('cms_incoming')
->directory('inhalte')
->visibility('private')
->maxSize(MediaUploadLimit::KILOBYTES)
->panelLayout('integrated')
->uploadProgressIndicatorPosition('center')
->helperText('Der Balken zeigt den Upload. Film, Hörstück, Bild oder PDF. Die Übernahme läuft danach im Hintergrund.');
}
public static function thumbnailField(): FileUpload
{
return FileUpload::make('thumbnail_upload')
->label('Vorschaubild')
->disk('cms_incoming')
->directory('vorschau')
->visibility('private')
->image()
->panelLayout('integrated')
->uploadProgressIndicatorPosition('center')
->helperText('Erscheint in der Anzeige und als Vorschlag in Modulen und Programmen. Eine Filmstelle wählst du beim Ansehen des Mediums. Speichern legt keine Fassung an.');
}
/**
* @param array<string, mixed> $data
*/
public static function create(array $data, bool $hold): ContentElement
{
$service = app(ContentService::class);
[$kind, $output] = self::shape($data['shape'] ?? null);
$kindId = self::contentKindId($data);
$incoming = null;
if ($output !== 'text') {
// Alles prüfen, bevor etwas angelegt wird: Eine abgelehnte Datei darf kein leeres Medium hinterlassen.
$incoming = IncomingFile::store($data['incoming'] ?? null);
if ($incoming === null) {
throw new DomainRuleException('Das Medium braucht eine Datei.');
}
$extension = strtolower(pathinfo($incoming, PATHINFO_EXTENSION));
$allowed = match ($data['shape'] ?? '') {
'audio' => ['mp3', 'm4a', 'wav', 'ogg'],
'bild' => ['png', 'jpg', 'jpeg', 'webp', 'gif'],
'document' => ['pdf'],
default => ['mp4', 'webm', 'mov', 'm4v'],
};
if (! in_array($extension, $allowed, true)) {
throw new DomainRuleException('Diese Datei passt nicht zur gewählten Art.');
}
if (! empty($data['without_version']) && in_array($output, ['bild', 'film', 'audio'], true)) {
app(PresentationFile::class)->validate($output, $incoming);
}
}
$element = $service->createElement($kind, $output, (string) $data['working_title']);
$element->editorial_content_kind_id = $kindId;
$element->save();
self::remember($element, $data);
if ($output === 'text') {
$body = FormattedText::canonical((string) ($data['body'] ?? ''));
if ($body === '') {
throw new DomainRuleException('Der Text braucht einen Inhalt.');
}
$hold
? $service->draftElementVersion($element, $body)
: $service->publishElementVersion($element, $body);
} else {
if (! empty($data['without_version']) && in_array($output, ['bild', 'film', 'audio'], true)) {
app(PresentationFile::class)->store($element, $incoming);
} else {
$metadata = ['incoming' => $incoming];
if ($hold) {
$metadata['hold'] = true;
$service->draftElementVersion($element, null, $metadata);
} else {
$service->publishElementVersion($element, null, $metadata);
}
}
}
self::queuePreview($element, $data);
return $element->fresh() ?? $element;
}
/**
* Die fachliche Materialart ist beim Anlegen Pflicht und muss für Medien zulässig und aktiv sein.
*
* @param array<string, mixed> $data
*/
private static function contentKindId(array $data): int
{
$id = $data['editorial_content_kind_id'] ?? null;
if (! filled($id) || ! ctype_digit((string) $id)) {
throw new DomainRuleException('Die fachliche Materialart fehlt.');
}
$error = app(EditorialVocabulary::class)->kindError('medium', (int) $id, null);
if ($error !== null) {
throw new DomainRuleException($error);
}
return (int) $id;
}
/**
* @param array<string, mixed> $data
*/
public static function update(ContentElement $element, array $data): ?ContentElementVersion
{
self::remember($element, $data);
$revised = null;
if ($element->output_class === 'text') {
$latest = $element->versions()->orderByDesc('number')->first();
$body = FormattedText::canonical((string) ($data['body'] ?? ''));
if ($latest instanceof ContentElementVersion && $body !== '') {
$revised = app(ContentService::class)->reviseElementContent($latest, $body);
}
}
self::queuePreview($element, $data);
return $revised;
}
/**
* @return array<string, string|null>
*/
public static function fill(ContentElement $element): array
{
$latest = $element->versions()->orderByDesc('number')->first();
return [
'working_title' => $element->working_title,
'description' => FormattedText::html($element->description),
'usage_note' => $element->usage_note,
'license_note' => $element->license_note,
'thumbnail_alt' => $element->thumbnail_alt,
'body' => EmbeddedImages::forEditor($latest?->body),
];
}
/**
* @param array<string, mixed> $data
*/
public static function remember(ContentElement $element, array $data): void
{
$description = FormattedText::same((string) ($data['description'] ?? ''), $element->description)
? $element->description
: (FormattedText::canonical((string) ($data['description'] ?? '')) ?: null);
app(ContentService::class)->describe($element, (string) $data['working_title'], $description);
app(IdentityProfile::class)->fill($element, [
'usage_note' => $data['usage_note'] ?? null,
'license_note' => $data['license_note'] ?? null,
'thumbnail_alt' => $data['thumbnail_alt'] ?? null,
], auth()->user());
}
/**
* @param array<string, mixed> $data
*/
public static function queuePreview(ContentElement $element, array $data): void
{
$path = self::previewPath($data['thumbnail_upload'] ?? null);
if ($path === null) {
return;
}
$element->thumbnail_error = null;
$element->save();
DeriveThumbnail::dispatch('element', $element->id, $path);
}
/**
* @return array{0: string, 1: string}
*/
private static function shape(mixed $shape): array
{
return match ($shape) {
'audio' => ['audio', 'audio'],
'bild' => ['bild', 'bild'],
'document' => ['dokument', 'document'],
'text' => ['text', 'text'],
'film' => ['film', 'film'],
default => throw new DomainRuleException('Die Art des Mediums fehlt.'),
};
}
private static function previewPath(mixed $value): ?string
{
if (is_array($value)) {
foreach ($value as $item) {
$stored = self::previewPath($item);
if ($stored !== null) {
return $stored;
}
}
return null;
}
if (! is_string($value) || $value === '' || str_contains($value, '..') || ! str_starts_with($value, 'vorschau/')) {
return null;
}
return Storage::disk('cms_incoming')->exists($value) ? $value : null;
}
}