From aeef7b5dbad4398a3ae255b78f6ca606e930594c Mon Sep 17 00:00:00 2001 From: Santeri Hurnanen Date: Wed, 18 Dec 2024 17:43:25 +0200 Subject: [PATCH] UHF-10737: Add command for cleaning previously added files --- src/Drush/Commands/FileCleanerCommands.php | 79 ++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 src/Drush/Commands/FileCleanerCommands.php diff --git a/src/Drush/Commands/FileCleanerCommands.php b/src/Drush/Commands/FileCleanerCommands.php new file mode 100644 index 0000000..57c3452 --- /dev/null +++ b/src/Drush/Commands/FileCleanerCommands.php @@ -0,0 +1,79 @@ + FALSE]): int { + $query = $this->connection->select('file_managed', 'f'); + + // Left join because file_usage might not exist. + $query->leftJoin('file_usage', 'fu', 'f.fid = fu.fid AND fu.count > 0'); + $query + ->fields('f', ['fid']) + // Permanent only files since temporary files are deleted automatically. + ->condition('f.status', FileInterface::STATUS_PERMANENT) + // Filter for rows for which file_usage was not found. + ->isNull('fu.fid'); + + foreach ($query->execute() as $result) { + /** @var \Drupal\file\FileInterface $file */ + $file = $this->entityTypeManager + ->getStorage('file') + ->load($result->fid); + + $url = $file->createFileUrl(FALSE); + $this->io()->writeln("Marking {$url} for deletion"); + + // Temporary files are eventually cleaned by hook_cron. + if ($options['no-dry-run']) { + $file->setTemporary(); + $file->save(); + } + } + + if (!$options['no-dry-run']) { + $this->io()->warning("Dry run: run with --no-dry-run to actually delete the files"); + } + + return self::EXIT_SUCCESS; + } + +}