Skip to content

Commit

Permalink
Added an option to the command for dry running
Browse files Browse the repository at this point in the history
  • Loading branch information
elevinskii committed Mar 5, 2024
1 parent 7556bec commit d6655bf
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
38 changes: 35 additions & 3 deletions Console/Command/RemoveMediaDuplicates.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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();
}

Expand All @@ -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();
Expand All @@ -79,6 +94,12 @@ protected function execute(InputInterface $input, OutputInterface $output)
}
}

if ($this->isDryRun($input)) {
$output->writeln(
'<comment>Dry mode enabled, no database operations performed</comment>'
);
}

$output->writeln(
sprintf(
'Number of images successfully removed: %d with size of %.2f MB',
Expand All @@ -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);
}
}
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit d6655bf

Please sign in to comment.