<?php
declare(strict_types=1);
namespace Juki\Bundle\AppBundle\EventListener;
use Hitso\Bundle\CommonBundle\Doctrine\Event\EntityEvent;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelInterface;
class CacheSubscriber implements EventSubscriberInterface
{
/**
* @var KernelInterface
*/
protected $kernel;
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
}
public static function getSubscribedEvents()
{
return [
'article.post_create' => 'onPostSave',
'article.post_update' => 'onPostSave',
'content.post_create' => 'onPostSave',
'content.post_update' => 'onPostSave',
'product.post_create' => 'onPostSave',
'product.post_update' => 'onPostSave',
'repo_file.post_update' => 'onPostSave',
];
}
public function onPostSave(EntityEvent $event): void
{
$cacheDir = $this->kernel->getCacheDir();
// opcache
if (function_exists('opcache_reset')) {
opcache_reset();
}
// apcu
if (function_exists('apcu_clear_cache')) {
apcu_clear_cache();
}
$application = new Application($this->kernel);
$application->setAutoExit(false);
$commands = [
[
'command' => 'cache:pool:clear',
'pools' => ['cache.global_clearer'],
],
[
'command' => 'doctrine:cache:clear-metadata',
],
[
'command' => 'doctrine:cache:clear-query',
],
[
'command' => 'doctrine:cache:clear-result',
],
];
foreach ($commands as $command) {
$input = new ArrayInput($command);
$output = new NullOutput();
$application->run($input, $output);
$done[] = $command['command'];
}
exec('rm -rf ' . $cacheDir . '-tmp');
exec('mv ' . $cacheDir . ' ' . $cacheDir . '-tmp');
exec('rm -rf ' . $cacheDir . '-tmp');
$this->kernel->getContainer()->get('session')->getFlashBag()->add('success', 'Cache został opróżniony.');
}
}