public function CacheControlEventSubscriber::setHeaderCacheControl in HTTP Cache Control 8.2
Same name and namespace in other branches
- 8 src/EventSubscriber/CacheControlEventSubscriber.php \Drupal\http_cache_control\EventSubscriber\CacheControlEventSubscriber::setHeaderCacheControl()
Set http cache control headers.
File
- src/
EventSubscriber/ CacheControlEventSubscriber.php, line 33
Class
- CacheControlEventSubscriber
- Subscriber for adding http cache control headers.
Namespace
Drupal\http_cache_control\EventSubscriberCode
public function setHeaderCacheControl(FilterResponseEvent $event) {
$config = $this->configFactory
->get('http_cache_control.settings');
$response = $event
->getResponse();
if ($variation = $config
->get('cache.http.vary')) {
$vary = $response
->getVary();
foreach (array_map('trim', explode(',', $variation)) as $header) {
$vary[] = $header;
}
if (!Settings::get('omit_vary_cookie')) {
$vary[] = 'Cookie';
}
$response
->setVary(implode(',', $vary));
}
if (!$response
->isCacheable()) {
return;
}
$ttl = $response
->getMaxAge();
switch ($response
->getStatusCode()) {
case 404:
$ttl = $config
->get('cache.http.404_max_age', $ttl);
break;
case 302:
$ttl = $config
->get('cache.http.302_max_age', $ttl);
break;
case 301:
$ttl = $config
->get('cache.http.301_max_age', $ttl);
break;
}
if ($ttl != $response
->getMaxAge()) {
$response
->setClientTtl($ttl);
$response
->setSharedMaxAge($ttl);
}
elseif ($ttl = $config
->get('cache.http.s_maxage')) {
$response
->setSharedMaxAge($ttl);
}
if ($response
->getStatusCode() >= 500) {
$response
->setSharedMaxAge($config
->get('cache.http.5xx_max_age'));
}
elseif ($response
->getStatusCode() < 400) {
// Add stale-if-error directive.
if ($seconds = $config
->get('cache.http.stale_if_error')) {
$response->headers
->addCacheControlDirective('stale-if-error', $seconds);
}
// Add stale-while-revalidate directive.
if ($seconds = $config
->get('cache.http.stale_while_revalidate')) {
$response->headers
->addCacheControlDirective('stale-while-revalidate', $seconds);
}
// Surrogate Control
$maxage = $config
->get('cache.surrogate.maxage');
$nostore = $config
->get('cache.surrogate.nostore');
if (!empty($maxage) || $nostore) {
$value = $nostore ? [
'no-store',
] : [];
if (!empty($maxage)) {
$value[] = 'max-age=' . $maxage;
}
$response->headers
->set('Surrogate-Control', implode(', ', $value));
}
}
}