<?php
/**
* Created by PhpStorm.
* User: albert
* Date: 28/08/18
* Time: 16:33
*/
namespace AWCmsBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class CacheListener implements EventSubscriberInterface
{
const NO_AUTO_CACHE_CONTROL_HEADER = 'Symfony-Session-NoAutoCacheControl';
private $private;
private $public;
private $maxAge;
private $mustRevalidate;
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * array('eventName' => 'methodName')
* * array('eventName' => array('methodName', $priority))
* * array('eventName' => array(array('methodName1', $priority), array('methodName2')))
*
* @return array The event names to listen to
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => [array('saveCacheData', -999),array('putCacheData', -1001)]
];
}
/**
* @param FilterResponseEvent $event
*/
public function saveCacheData(FilterResponseEvent $event)
{
$response = $event->getResponse();
if ($response->headers->has(self::NO_AUTO_CACHE_CONTROL_HEADER)) {
$this->private = $response->headers->getCacheControlDirective('private');
$this->public = $response->headers->getCacheControlDirective('public');
$this->maxAge = $response->headers->getCacheControlDirective('max-age');
$this->mustRevalidate = $response->headers->getCacheControlDirective('must-revalidate');
}
}
/**
* @param FilterResponseEvent $event
*/
public function putCacheData(FilterResponseEvent $event)
{
$response = $event->getResponse();
if ($response->headers->has(self::NO_AUTO_CACHE_CONTROL_HEADER)) {
if ($this->public || $this->private === false || $this->private === null) {
$response->setPublic();
}
if($this->maxAge !== null) {
$response->setMaxAge($this->maxAge);
}
if($this->mustRevalidate !== null && $this->mustRevalidate !== true) {
$response->headers->removeCacheControlDirective('must-revalidate');
}
$response->headers->remove(self::NO_AUTO_CACHE_CONTROL_HEADER);
}
}
}