CacheableResponseSubscriber.php in Pantheon Advanced Page Cache 8
File
src/EventSubscriber/CacheableResponseSubscriber.php
View source
<?php
namespace Drupal\pantheon_advanced_page_cache\EventSubscriber;
use Drupal\Core\Cache\CacheableResponseInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Log\LoggerInterface;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Config\ConfigFactoryInterface;
class CacheableResponseSubscriber implements EventSubscriberInterface {
protected $logger;
protected $configFactory;
public function __construct(LoggerInterface $logger, ConfigFactoryInterface $config_factory = NULL) {
if (!$config_factory instanceof ConfigFactoryInterface) {
@trigger_error('Not passing the config factory service as the second parameter to ' . __METHOD__ . ' is deprecated in pantheon_advanced_page_cache:8.x-1.2 and will throw a type error in pantheon_advanced_page_cache:8.x-2.0. Pass an instance of \\Drupal\\Core\\Config\\ConfigFactoryInterface. See https://www.drupal.org/node/2944229', E_USER_DEPRECATED);
$config_factory = \Drupal::service('config.factory');
}
$this->logger = $logger;
$this->configFactory = $config_factory;
}
public function getOverrideListTagsSetting() {
$config = $this->configFactory
->get('pantheon_advanced_page_cache.settings');
if ($config
->get('override_list_tags') === FALSE) {
return FALSE;
}
return TRUE;
}
public function onRespond(FilterResponseEvent $event) {
if (!$event
->isMasterRequest()) {
return;
}
$response = $event
->getResponse();
if ($response instanceof CacheableResponseInterface) {
$tags = $response
->getCacheableMetadata()
->getCacheTags();
if ($this
->getOverrideListTagsSetting()) {
foreach ($tags as $key => $tag) {
$tags[$key] = str_replace('_list', '_emit_list', $tag);
}
}
$tags_string = implode(' ', $tags);
if (25000 < strlen($tags_string)) {
$tags_string = substr($tags_string, 0, 25000);
$tags_string = substr($tags_string, 0, strrpos($tags_string, ' '));
$this->logger
->log(RfcLogLevel::WARNING, 'More cache tags were present than could be passed in the Surrogate-Key HTTP Header due to length constraints. To avoid a 502 error the list of surrogate keys was trimmed to a maximum length of 25,000 bytes. Since keys beyond the 25,000 maximum were removed this page will not be cleared from the cache when any of the removed keys are cleared (usually by entity save operations) as they have been stripped from the surrogate key header. See https://www.drupal.org/project/pantheon_advanced_page_cache/issues/2973861 for more information about how you can filter out redundant or unnecessary cache metadata.');
}
$response->headers
->set('Surrogate-Key', $tags_string);
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = [
'onRespond',
];
return $events;
}
}