From d6655bf489c1c6f470f5a4cd93df9f9e3b316c78 Mon Sep 17 00:00:00 2001 From: Evgeny Levinsky Date: Tue, 5 Mar 2024 15:29:29 -0600 Subject: [PATCH] Added an option to the command for dry running --- Console/Command/RemoveMediaDuplicates.php | 38 +++++++++++++++++++++-- README.md | 4 +++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/Console/Command/RemoveMediaDuplicates.php b/Console/Command/RemoveMediaDuplicates.php index 308ff5f..10a0ad6 100644 --- a/Console/Command/RemoveMediaDuplicates.php +++ b/Console/Command/RemoveMediaDuplicates.php @@ -12,10 +12,16 @@ use Psr\Log\LoggerInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class RemoveMediaDuplicates extends Command { + /** + * List of available options + */ + private const OPTION_DRY_RUN = 'dry-run'; + /** * @param OriginFinder $originFinder * @param ImageBuilder $imageBuilder @@ -44,6 +50,13 @@ protected function configure() ->setName('catalog:images:remove-duplicates') ->setDescription('Searches for media duplicates in database and removes them'); + $this->addOption( + self::OPTION_DRY_RUN, + null, + InputOption::VALUE_NONE, + 'Performs dry running without any operations with database' + ); + parent::configure(); } @@ -68,9 +81,11 @@ protected function execute(InputInterface $input, OutputInterface $output) $duplicateImage = $this->imageBuilder->create($image->getValue()); $originImage = $this->originFinder->getOriginImage($duplicateImage); - $this->imageResource->save( - $image->setValue($originImage->getCatalogPath()) - ); + if (!$this->isDryRun($input)) { + $this->imageResource->save( + $image->setValue($originImage->getCatalogPath()) + ); + } $removedImages[] = $duplicateImage; $totalSize += $duplicateImage->getFileSize(); @@ -79,6 +94,12 @@ protected function execute(InputInterface $input, OutputInterface $output) } } + if ($this->isDryRun($input)) { + $output->writeln( + 'Dry mode enabled, no database operations performed' + ); + } + $output->writeln( sprintf( 'Number of images successfully removed: %d with size of %.2f MB', @@ -89,4 +110,15 @@ protected function execute(InputInterface $input, OutputInterface $output) return Cli::RETURN_SUCCESS; } + + /** + * If the command executes in dry run mode + * + * @param InputInterface $input + * @return bool + */ + private function isDryRun(InputInterface $input): bool + { + return $input->getOption(self::OPTION_DRY_RUN); + } } diff --git a/README.md b/README.md index 573e189..00585e9 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,10 @@ original path. That's easy - `bin/magento catalog:images:remove-duplicates` +Possible options: + +- `--dry-run` - performs dry running without any operations with database + **Warning** Please create dumps of below listed tables, for being able to revert changes if something goes wrong.