|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Sherlockode\AdvancedFormBundle\Command; |
| 4 | + |
| 5 | +use Sherlockode\AdvancedFormBundle\Storage\FilesystemStorage; |
| 6 | +use Symfony\Component\Console\Command\Command; |
| 7 | +use Symfony\Component\Console\Input\InputInterface; |
| 8 | +use Symfony\Component\Console\Input\InputOption; |
| 9 | +use Symfony\Component\Console\Output\OutputInterface; |
| 10 | + |
| 11 | +/** |
| 12 | + * Class RemoveTemporaryFileCommand |
| 13 | + */ |
| 14 | +class RemoveTemporaryFileCommand extends Command |
| 15 | +{ |
| 16 | + /** |
| 17 | + * RemoveTemporaryFileCommand constructor. |
| 18 | + * |
| 19 | + * @param FilesystemStorage $storage |
| 20 | + */ |
| 21 | + public function __construct(FilesystemStorage $storage) |
| 22 | + { |
| 23 | + parent::__construct(); |
| 24 | + $this->storage = $storage; |
| 25 | + } |
| 26 | + |
| 27 | + protected function configure() |
| 28 | + { |
| 29 | + $this |
| 30 | + ->setName('sherlockode:afb:cleanup-tmp') |
| 31 | + ->setDescription('Remove all temporary files.') |
| 32 | + ->addOption('older-than', null, InputOption::VALUE_REQUIRED) |
| 33 | + ; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @param InputInterface $input |
| 38 | + * @param OutputInterface $output |
| 39 | + * |
| 40 | + * @return int |
| 41 | + */ |
| 42 | + protected function execute(InputInterface $input, OutputInterface $output) |
| 43 | + { |
| 44 | + $olderThan = $input->getOption('older-than'); |
| 45 | + $limit = null; |
| 46 | + if ($olderThan) { |
| 47 | + $limit = clone new \DateTime(); |
| 48 | + $limit->sub(new \DateInterval(sprintf('P%s', strtoupper($olderThan)))); |
| 49 | + } |
| 50 | + |
| 51 | + $files = $this->storage->all(); |
| 52 | + $count = 0; |
| 53 | + |
| 54 | + foreach ($this->storage->all() as $filePath) { |
| 55 | + if ($limit) { |
| 56 | + $file = $this->storage->getFileObject($filePath); |
| 57 | + if ($file->getCTime() < $limit->getTimestamp()) { |
| 58 | + $this->storage->remove($filePath); |
| 59 | + $count++; |
| 60 | + } |
| 61 | + } else { |
| 62 | + $this->storage->remove($filePath); |
| 63 | + $count++; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + $output->writeln(sprintf('<info>%s files has been removed</info>', $count)); |
| 68 | + |
| 69 | + return 0; |
| 70 | + } |
| 71 | +} |
0 commit comments