From 27c632034a7f706209c1e3b97c28b07b680ff2b7 Mon Sep 17 00:00:00 2001 From: Marc Jauvin Date: Thu, 18 Mar 2021 00:20:39 -0400 Subject: [PATCH] implement artisan october:util purge orphans (#5465) * implement october:util purge orphan --- modules/system/console/OctoberUtil.php | 34 +++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/modules/system/console/OctoberUtil.php b/modules/system/console/OctoberUtil.php index 14700a31f..daa662943 100644 --- a/modules/system/console/OctoberUtil.php +++ b/modules/system/console/OctoberUtil.php @@ -99,6 +99,7 @@ class OctoberUtil 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 OctoberUtil 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.'); + } } /**