93 lines
2.7 KiB
PHP
93 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\AuditionEtude;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class EtudesCleanup extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'etudes:cleanup {--dry-run : Show what would be deleted without actually deleting}';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = 'Clean up orphaned etude records and PDF files';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*/
|
|
public function handle(): int
|
|
{
|
|
$dryRun = $this->option('dry-run');
|
|
|
|
if ($dryRun) {
|
|
$this->info('Running in dry-run mode - no changes will be made');
|
|
}
|
|
|
|
$this->info('Starting etudes cleanup...');
|
|
$this->newLine();
|
|
|
|
// Part 1: Remove database records with missing PDF files
|
|
$this->info('Checking for database records with missing PDF files...');
|
|
$orphanedRecords = 0;
|
|
|
|
AuditionEtude::chunk(100, function ($etudes) use (&$orphanedRecords, $dryRun) {
|
|
foreach ($etudes as $etude) {
|
|
if (! Storage::disk('public')->exists($etude->file_path)) {
|
|
$this->warn("Missing file: {$etude->file_path} (Record ID: {$etude->id})");
|
|
$orphanedRecords++;
|
|
|
|
if (! $dryRun) {
|
|
$etude->delete();
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
if ($orphanedRecords > 0) {
|
|
$action = $dryRun ? 'would be' : 'were';
|
|
$this->info("✓ {$orphanedRecords} orphaned database record(s) {$action} removed");
|
|
} else {
|
|
$this->info('✓ No orphaned database records found');
|
|
}
|
|
|
|
$this->newLine();
|
|
|
|
// Part 2: Remove PDF files not referenced in the database
|
|
$this->info('Checking for PDF files not referenced in the database...');
|
|
|
|
$referencedPaths = AuditionEtude::pluck('file_path')->toArray();
|
|
$allFiles = Storage::disk('public')->files('etudes');
|
|
$orphanedFiles = array_diff($allFiles, $referencedPaths);
|
|
|
|
if (count($orphanedFiles) > 0) {
|
|
foreach ($orphanedFiles as $file) {
|
|
$this->warn("Orphaned file: {$file}");
|
|
|
|
if (! $dryRun) {
|
|
Storage::disk('public')->delete($file);
|
|
}
|
|
}
|
|
|
|
$action = $dryRun ? 'would be' : 'were';
|
|
$this->info('✓ '.count($orphanedFiles)." orphaned file(s) {$action} removed");
|
|
} else {
|
|
$this->info('✓ No orphaned files found');
|
|
}
|
|
|
|
$this->newLine();
|
|
$this->info('Cleanup completed!');
|
|
|
|
return Command::SUCCESS;
|
|
}
|
|
}
|