resq/src/Command/UploadCleanupCommand.php

99 lines
2.7 KiB
PHP

<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Doctrine\Common\Persistence\ObjectManager;
use App\Entity\Rider;
use App\Entity\Battery;
use App\Service\FileUploader;
use DirectoryIterator;
class UploadCleanupCommand extends Command
{
private $encoder_factory;
private $object_manager;
public function __construct(ObjectManager $om, Filesystem $fs, FileUploader $uploader)
{
$this->object_manager = $om;
$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->object_manager;
$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!');
}
}