core/lib/Thelia/Action/Cache.php line 47

  1. <?php
  2. /*
  3.  * This file is part of the Thelia package.
  4.  * http://www.thelia.net
  5.  *
  6.  * (c) OpenStudio <info@thelia.net>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Thelia\Action;
  12. use Symfony\Component\Cache\Adapter\AdapterInterface;
  13. use Symfony\Component\Console\ConsoleEvents;
  14. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  15. use Symfony\Component\Filesystem\Filesystem;
  16. use Symfony\Component\HttpKernel\KernelEvents;
  17. use Thelia\Core\Event\Cache\CacheEvent;
  18. use Thelia\Core\Event\TheliaEvents;
  19. /**
  20.  * Class Cache.
  21.  *
  22.  * @author Manuel Raynaud <manu@raynaud.io>
  23.  * @author Gilles Bourgeat <gilles.bourgeat@gmail.com>
  24.  */
  25. class Cache extends BaseAction implements EventSubscriberInterface
  26. {
  27.     /** @var AdapterInterface */
  28.     protected $adapter;
  29.     /**
  30.      * @var CacheEvent[]
  31.      */
  32.     protected $onTerminateCacheClearEvents = [];
  33.     /**
  34.      * CacheListener constructor.
  35.      */
  36.     public function __construct(AdapterInterface $adapter)
  37.     {
  38.         $this->adapter $adapter;
  39.     }
  40.     public function cacheClear(CacheEvent $event): void
  41.     {
  42.         if (!$event->isOnKernelTerminate()) {
  43.             $this->execCacheClear($event);
  44.             return;
  45.         }
  46.         $findDir false;
  47.         foreach ($this->onTerminateCacheClearEvents as $cacheEvent) {
  48.             if ($cacheEvent->getDir() === $event->getDir()) {
  49.                 $findDir true;
  50.                 break;
  51.             }
  52.         }
  53.         if (!$findDir) {
  54.             $this->onTerminateCacheClearEvents[] = $event;
  55.         }
  56.     }
  57.     public function onTerminate(): void
  58.     {
  59.         foreach ($this->onTerminateCacheClearEvents as $cacheEvent) {
  60.             $this->execCacheClear($cacheEvent);
  61.         }
  62.     }
  63.     protected function execCacheClear(CacheEvent $event): void
  64.     {
  65.         $this->adapter->clear();
  66.         $dir $event->getDir();
  67.         $fs = new Filesystem();
  68.         $fs->remove($dir);
  69.     }
  70.     /**
  71.      * {@inheritdoc}
  72.      */
  73.     public static function getSubscribedEvents()
  74.     {
  75.         return [
  76.             TheliaEvents::CACHE_CLEAR => ['cacheClear'128],
  77.             KernelEvents::TERMINATE => ['onTerminate'128],
  78.             ConsoleEvents::TERMINATE => ['onTerminate'128],
  79.         ];
  80.     }
  81. }