add('news', 'Neuigkeiten', * scan: fn (NewsPost $post) => [ * ['context' => 'Titelbild', 'label' => $post->title, 'url' => '/…', 'draft' => false, 'paths' => [$post->cover_path]], * ], * all: fn (callable $each) => NewsPost::query()->chunkById(100, fn ($posts) => $posts->each($each)), * ); * $usages->watch('news', NewsPost::class, ['cover_path', 'body_html']); * * scan() liefert je Stelle Pfade im Speicher „uploads“ (ImagePaths hilft beim * Auslesen von Pagebuilder-JSON und HTML). Unbekannte, aber vorhandene * Bilddateien werden dabei automatisch in die Mediathek übernommen – so landen * auch Uploads aus Formularen, die die Mediathek nicht kennen, dort. */ class MediaUsages { /** @var array */ private array $sources = []; private bool $ready = false; public function __construct(private readonly Dispatcher $events) {} /** * @param callable(Model): list, source_id?: int}> $scan * @param (callable(callable(Model): void): void)|null $all ruft $each für jede Quelle auf (für „Neu einlesen“) */ public function add(string $type, string $label, callable $scan, ?callable $all = null): void { $this->sources[$type] = ['label' => $label, 'scan' => $scan, 'all' => $all]; } /** * Verwendungen bei jedem Speichern/Löschen des Modells aktualisieren. * * @param class-string $model * @param list $columns nur neu berechnen, wenn sich eine dieser Spalten ändert (leer = immer) */ public function watch(string $type, string $model, array $columns = []): void { $this->events->listen("eloquent.saved: {$model}", function (Model $record) use ($type, $columns) { if ($columns === [] || $record->wasRecentlyCreated || $record->wasChanged($columns)) { $this->sync($type, $record); } }); $this->events->listen("eloquent.deleted: {$model}", fn (Model $record) => $this->forget($type, (int) $record->getKey())); } /** * @return array Typ => Bezeichnung (z. B. „pages“ => „Seiten“) */ public function labels(): array { return array_map(fn (array $source) => $source['label'], $this->sources); } public function has(string $type): bool { return isset($this->sources[$type]); } /** * Verwendungen einer Quelle neu erfassen. Fehler werden nur protokolliert – * Speichern von Inhalten darf nie an der Mediathek scheitern. */ public function sync(string $type, Model $record): void { if (! isset($this->sources[$type]) || ! $this->tablesReady()) { return; } try { $entries = ($this->sources[$type]['scan'])($record); $paths = []; foreach ($entries as $entry) { foreach ($entry['paths'] ?? [] as $path) { if (is_string($path) && $path !== '') { $paths[] = $path; } } } $ids = app(MediaLibrary::class)->ensureRegistered(array_values(array_unique($paths))); $rows = []; $now = now(); // Nicht-Entwürfe zuerst, damit dieselbe Stelle nicht doppelt als Entwurf erscheint. usort($entries, fn (array $a, array $b) => (int) ($a['draft'] ?? false) <=> (int) ($b['draft'] ?? false)); foreach ($entries as $entry) { foreach (array_unique(array_filter((array) ($entry['paths'] ?? []), 'is_string')) as $path) { if (! isset($ids[$path])) { continue; } $sourceId = (int) ($entry['source_id'] ?? $record->getKey()); $key = $ids[$path].'|'.$sourceId.'|'.$entry['context']; if (isset($rows[$key])) { continue; } $rows[$key] = [ 'media_id' => $ids[$path], 'source_type' => $type, 'source_id' => $sourceId, 'context' => mb_substr((string) $entry['context'], 0, 80), 'label' => mb_substr((string) ($entry['label'] ?? ''), 0, 250), 'url' => isset($entry['url']) ? mb_substr((string) $entry['url'], 0, 1000) : null, 'draft' => (bool) ($entry['draft'] ?? false), 'created_at' => $now, ]; } } DB::transaction(function () use ($type, $record, $rows) { MediaUsage::query()->where('source_type', $type)->where('source_id', $record->getKey())->delete(); foreach (array_chunk(array_values($rows), 200) as $chunk) { MediaUsage::query()->insert($chunk); } }); } catch (Throwable $e) { report($e); } } public function forget(string $type, int $id): void { if (! $this->tablesReady()) { return; } try { MediaUsage::query()->where('source_type', $type)->where('source_id', $id)->delete(); } catch (Throwable $e) { report($e); } } /** * Alle Verwendungen neu erfassen (dabei referenzierte Dateien übernehmen). * * @return int Anzahl der durchsuchten Quellen */ public function rebuild(): int { if (! $this->tablesReady()) { return 0; } $count = 0; // Verwendungen von Quellen, die es nicht mehr gibt (z. B. Plugin entfernt), fallen weg. MediaUsage::query()->whereNotIn('source_type', array_keys($this->sources) ?: [''])->delete(); foreach ($this->sources as $type => $source) { if (! $source['all']) { continue; } try { MediaUsage::query()->where('source_type', $type)->delete(); ($source['all'])(function (Model $record) use ($type, &$count) { $this->sync($type, $record); $count++; }); } catch (Throwable $e) { report($e); } } return $count; } private function tablesReady(): bool { // Nur „ja“ merken: Während eines Updates entstehen die Tabellen erst mittendrin. return $this->ready = $this->ready || Schema::hasTable('media_usages'); } }