Files
laraundfelix/app/Filament/Support/MediumForm.php
T
LarsandClaude Sonnet 5.5 9fbd933e1e Speichere formatierte Texte als bereinigtes HTML mit einem Editor (ADR-50)
Ein Baustein (FormattedText) bereinigt, bringt Werte in die kanonische Form und
wandelt Klartext des Altbestands; RichField ist der eine Editor, ManagesRichFields
verbindet ihn mit den Arbeitsplätzen. Formatiert sind Texte der Übungen und
Textbausteine, Kurzbeschreibung und Beschreibung, Lernziel und Ausstattung.
Mitgliederansicht und PDF zeigen fett, kursiv, Listen, Überschrift, Zitat und Link
(PDF: schräge Schnitte, nur wenn gebraucht). Das Livewire-Limit für verschachtelte
Pfade steigt auf 30, weil Aufzählungen sonst abgelehnt werden.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 23:45:54 +01:00

265 lines
9.9 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\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('shape')->label('Was ist das?')->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);
$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']);
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;
}
/**
* @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' => FormattedText::html($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;
}
}