small cli tool to purge unused avatar uploads
This commit is contained in:
parent
f48529b743
commit
763e3f4918
|
@ -0,0 +1,72 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Command;
|
||||||
|
|
||||||
|
use App\Repository\UserRepository;
|
||||||
|
use Symfony\Component\Console\Attribute\AsCommand;
|
||||||
|
use Symfony\Component\Console\Command\Command;
|
||||||
|
use Symfony\Component\Console\Input\InputInterface;
|
||||||
|
use Symfony\Component\Console\Output\OutputInterface;
|
||||||
|
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||||
|
|
||||||
|
#[AsCommand(
|
||||||
|
name: 'cron:run',
|
||||||
|
description: 'Cleanup stale avatars',
|
||||||
|
)]
|
||||||
|
class CronRunCommand extends Command
|
||||||
|
{
|
||||||
|
public function __construct(private readonly UserRepository $userRepository)
|
||||||
|
{
|
||||||
|
parent::__construct();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function configure(): void
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
$this
|
||||||
|
->addArgument('arg1', InputArgument::OPTIONAL, 'Argument description')
|
||||||
|
->addOption('option1', null, InputOption::VALUE_NONE, 'Option description')
|
||||||
|
;
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||||
|
{
|
||||||
|
$io = new SymfonyStyle($input, $output);
|
||||||
|
|
||||||
|
$verbose = $input->getOption('verbose');
|
||||||
|
|
||||||
|
$staleCount = $this->deleteStaleAvatars();
|
||||||
|
|
||||||
|
if ($verbose) {
|
||||||
|
if ($staleCount > 0) {
|
||||||
|
$io->writeln("There were " . $staleCount . " stale avatars.");
|
||||||
|
} else {
|
||||||
|
$io->writeln("There were no stale avatars younger than 24 hours.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Command::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function deleteStaleAvatars(): int
|
||||||
|
{
|
||||||
|
$avatarDir = dirname(__DIR__, 2) . '/public/uploads/avatars';
|
||||||
|
$keepTime = 86400; // 24 hours
|
||||||
|
$deletedFiles = 0;
|
||||||
|
|
||||||
|
foreach (glob($avatarDir . '/*') as $entry) {
|
||||||
|
$filectime = filectime($entry);
|
||||||
|
if ($filectime && $filectime + $keepTime < time()) {
|
||||||
|
// check if it in use
|
||||||
|
if ($user = $this->userRepository->findOneBy(['avatar' => basename($entry)])) {
|
||||||
|
echo basename($entry) . " is in use by: " . $user->getUserIdentifier() . PHP_EOL;
|
||||||
|
}
|
||||||
|
unlink($entry);
|
||||||
|
$deletedFiles++;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return $deletedFiles;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue