src/EventSubscriber/TempGarbageCollectorEventSubscriber.php line 40

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\Filesystem\Filesystem;
  5. use Symfony\Component\Finder\Finder;
  6. use Symfony\Component\HttpKernel\Event\TerminateEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\HttpKernel\KernelInterface;
  9. /**
  10.  * Removes temporary elements older than 10 minutes.
  11.  */
  12. class TempGarbageCollectorEventSubscriber implements EventSubscriberInterface
  13. {
  14.     private string $rootDirectory;
  15.     public function __construct(KernelInterface $kernel)
  16.     {
  17.         $this->rootDirectory $kernel->getProjectDir();
  18.     }
  19.     /** @inheritdoc */
  20.     public static function getSubscribedEvents()
  21.     {
  22.         return [
  23.             KernelEvents::TERMINATE => ['doGC'0]
  24.         ];
  25.     }
  26.     /**
  27.      * Removes temporary elements older than 10 minutes.
  28.      *
  29.      * @param TerminateEvent $event triggered event (not used).
  30.      *
  31.      * @return void
  32.      */
  33.     public function doGC(TerminateEvent $event): void
  34.     {
  35.         $tmpPath sprintf('%s/var/tmp'$this->rootDirectory);
  36.         $fs = new Filesystem();
  37.         if (true === $fs->exists($tmpPath)) {
  38.             foreach ((new Finder())->in($tmpPath)->files()->date('< now - 10 minutes') as $file) {
  39.                 $fs->remove($file->getRealPath());
  40.             }
  41.         }
  42.     }
  43. }