src/Juki/Bundle/AppBundle/EventListener/CacheSubscriber.php line 39

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Juki\Bundle\AppBundle\EventListener;
  4. use Hitso\Bundle\CommonBundle\Doctrine\Event\EntityEvent;
  5. use Symfony\Bundle\FrameworkBundle\Console\Application;
  6. use Symfony\Component\Console\Input\ArrayInput;
  7. use Symfony\Component\Console\Output\NullOutput;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpKernel\KernelInterface;
  10. class CacheSubscriber implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var KernelInterface
  14.      */
  15.     protected $kernel;
  16.     public function __construct(KernelInterface $kernel)
  17.     {
  18.         $this->kernel $kernel;
  19.     }
  20.     public static function getSubscribedEvents()
  21.     {
  22.         return [
  23.             'article.post_create'   => 'onPostSave',
  24.             'article.post_update'   => 'onPostSave',
  25.             'content.post_create'   => 'onPostSave',
  26.             'content.post_update'   => 'onPostSave',
  27.             'product.post_create'   => 'onPostSave',
  28.             'product.post_update'   => 'onPostSave',
  29.             'repo_file.post_update' => 'onPostSave',
  30.         ];
  31.     }
  32.     public function onPostSave(EntityEvent $event): void
  33.     {
  34.         $cacheDir $this->kernel->getCacheDir();
  35.         // opcache
  36.         if (function_exists('opcache_reset')) {
  37.             opcache_reset();
  38.         }
  39.         // apcu
  40.         if (function_exists('apcu_clear_cache')) {
  41.             apcu_clear_cache();
  42.         }
  43.         $application = new Application($this->kernel);
  44.         $application->setAutoExit(false);
  45.         $commands = [
  46.             [
  47.                 'command' => 'cache:pool:clear',
  48.                 'pools'   => ['cache.global_clearer'],
  49.             ],
  50.             [
  51.                 'command' => 'doctrine:cache:clear-metadata',
  52.             ],
  53.             [
  54.                 'command' => 'doctrine:cache:clear-query',
  55.             ],
  56.             [
  57.                 'command' => 'doctrine:cache:clear-result',
  58.             ],
  59.         ];
  60.         foreach ($commands as $command) {
  61.             $input = new ArrayInput($command);
  62.             $output = new NullOutput();
  63.             $application->run($input$output);
  64.             $done[] = $command['command'];
  65.         }
  66.         exec('rm -rf ' $cacheDir '-tmp');
  67.         exec('mv ' $cacheDir ' ' $cacheDir '-tmp');
  68.         exec('rm -rf ' $cacheDir '-tmp');
  69.         $this->kernel->getContainer()->get('session')->getFlashBag()->add('success''Cache został opróżniony.');
  70.     }
  71. }