Implement artisan winter:util purge orphans (#44)

Credit to @mjauvin
This commit is contained in:
Marc Jauvin 2021-03-22 16:36:05 -04:00 committed by GitHub
parent 06b91d16f2
commit 4e2fa8d047
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -99,6 +99,7 @@ class WinterUtil extends Command
['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'],
['debug', null, InputOption::VALUE_NONE, 'Run the operation in debug / development mode.'],
['projectId', null, InputOption::VALUE_REQUIRED, 'Specify a projectId for set project'],
['missing-files', null, InputOption::VALUE_NONE, 'Purge system_files records for missing storage files'],
];
}
@ -339,7 +340,38 @@ class WinterUtil extends Command
return;
}
// @todo
$isDebug = $this->option('debug');
$orphanedFiles = 0;
$isLocalStorage = Config::get('cms.storage.uploads.disk', 'local') === 'local';
$files = FileModel::whereDoesntHaveMorph('attachment', '*')
->orWhereNull('attachment_id')
->orWhereNull('attachment_type')
->get();
foreach ($files as $file) {
if (!$isDebug) {
$file->delete();
}
$orphanedFiles += 1;
}
if ($this->option('missing-files') && $isLocalStorage) {
foreach (FileModel::all() as $file) {
if (!File::exists($file->getLocalPath())) {
if (!$isDebug) {
$file->delete();
}
$orphanedFiles += 1;
}
}
}
if ($orphanedFiles > 0) {
$this->comment(sprintf('Successfully deleted %d orphaned record(s).', $orphanedFiles));
} else {
$this->comment('No records to purge.');
}
}
/**