em = $em; $this->filesystem = $fs; $this->uploader = $uploader; parent::__construct(); } protected function configure() { $this->setName('upload:cleanup') ->setDescription('Clean up uploads folder.') ->setHelp('Cleans up all orphaned files from the uploads folder.'); } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Retrieving file whitelist...'); // get all image filenames $em = $this->em; $riders = $em->getRepository(Rider::class)->findAll(); $whitelist = ['.gitkeep']; if (!empty($riders)) { foreach ($riders as $obj) { $image = $obj->getImageFile(); if (!empty($image)) { $whitelist[] = $image; } } } $batteries = $em->getRepository(Battery::class)->findAll(); $whitelist = ['.gitkeep']; if (!empty($batteries)) { foreach ($batteries as $obj) { $image = $obj->getImageFile(); if (!empty($image)) { $whitelist[] = $image; } } } $directory = $this->uploader->getTargetDir(); // get all files in folder $files = new DirectoryIterator($directory); $i = 0; // delete all files that are not linked foreach ($files as $file) { $filename = $file->getFilename(); if (!in_array($filename, $whitelist) && $file->isFile()) { try { $this->filesystem->remove($directory . '/' . $filename); } catch (IOExceptionInterface $e) { $output->writeln('An error occurred while deleting the file "' . $filename . '"!'); } $i++; } } if ($i > 0) $output->writeln('Deleted ' . $i . ' orphaned file(s). Done!'); else $output->writeln('No files found. Done!'); return 0; } }