<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\KernelInterface;
/**
* Removes temporary elements older than 10 minutes.
*/
class TempGarbageCollectorEventSubscriber implements EventSubscriberInterface
{
private string $rootDirectory;
public function __construct(KernelInterface $kernel)
{
$this->rootDirectory = $kernel->getProjectDir();
}
/** @inheritdoc */
public static function getSubscribedEvents()
{
return [
KernelEvents::TERMINATE => ['doGC', 0]
];
}
/**
* Removes temporary elements older than 10 minutes.
*
* @param TerminateEvent $event triggered event (not used).
*
* @return void
*/
public function doGC(TerminateEvent $event): void
{
$tmpPath = sprintf('%s/var/tmp', $this->rootDirectory);
$fs = new Filesystem();
if (true === $fs->exists($tmpPath)) {
foreach ((new Finder())->in($tmpPath)->files()->date('< now - 10 minutes') as $file) {
$fs->remove($file->getRealPath());
}
}
}
}