option('orphans') ? $this->orphans() : $this->unused($library); } private function unused(MediaLibrary $library): int { $days = max(0, (int) $this->option('older-than')); $candidates = Media::query()->where('created_at', '<', now()->subDays($days))->orderBy('id')->get(); $counts = $library->usageCounts($candidates); $found = $deleted = $failed = 0; foreach ($candidates as $media) { if (($counts[$media->id] ?? 0) > 0) { continue; } $found++; $label = "#{$media->id} {$media->filename} (".round($media->size / 1024).' KB)'; if (! $this->option('delete')) { $this->line("{$label}: not used."); continue; } try { $library->delete($media); $this->line("{$label}: deleted."); $deleted++; } catch (Throwable $e) { $this->error("{$label}: could not be deleted ({$e->getMessage()})"); $failed++; } } $this->info($this->option('delete') ? "Deleted {$deleted}, failed {$failed}." : "{$found} not used. Run again with --delete to remove them."); return $failed === 0 ? self::SUCCESS : self::FAILURE; } private function orphans(): int { $name = (string) ($this->option('disk') ?: config('manager.media.disk')); $known = Media::query()->where('disk', $name)->pluck('location')->flip(); $disk = Storage::disk($name); try { $files = $disk->allFiles('media'); } catch (Throwable) { $files = []; } if ($files === [] && Media::query()->where('disk', $name)->exists()) { $this->warn("The disk `{$name}` cannot list its files (or has none), so there is nothing to compare."); return self::SUCCESS; } $found = 0; foreach ($files as $file) { if ($known->has($file)) { continue; } $found++; $this->line($this->option('delete') ? "{$file}: ".($disk->delete($file) ? 'deleted.' : 'could not be deleted.') : "{$file}: no row knows it."); } $this->info($this->option('delete') ? "Looked at {$found} unknown files." : "{$found} files that no row knows. Run again with --delete to remove them."); return self::SUCCESS; } }