Skip to content

Instantly share code, notes, and snippets.

@cmcintosh
Created December 1, 2019 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmcintosh/e311f3c0b166c5258156d3aa69418f45 to your computer and use it in GitHub Desktop.
Save cmcintosh/e311f3c0b166c5258156d3aa69418f45 to your computer and use it in GitHub Desktop.
/**
* Sets expires and max-age for bubbled-up max-age values that are > 0.
*
* @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
* The response event.
*
* @throws \Exception
* Thrown when \DateTime() cannot create a new date object from the
* arguments passed in.
*/
public function onResponse(FilterResponseEvent $event) {
// Don't bother proceeding on sub-requests.
if (!$event->isMasterRequest()) {
return;
}
$response = $event->getResponse();
// Nothing to do here if there isn't cacheable metadata available.
if (!($response instanceof CacheableResponseInterface)) {
return;
}
// Bail out early if this isn't an anonymous request.
if ($this->user->isAuthenticated()) {
return;
}
// Do some other crazy business logic, if necessary.
$max_age = (int) $response->getCacheableMetadata()->getCacheMaxAge();
if ($max_age !== Cache::PERMANENT) {
// Here we do 2 things: 1) we forward the bubbled max-age to the response
// Cache-Control "max-age" directive (which would otherwise take the
// site-wide `system.performance:cache.page.max_age` value; and 2) we
// replicate that into the "Expires" header, which is unfortunately what
// Drupal's internal page cache will respect. The former is for the outer
// world (proxies, CDNs, etc), and the latter for our own page cache.
$response->setMaxAge($max_age);
$date = new \DateTime('@' . ($this->time->getRequestTime() + $max_age));
$response->setExpires($date);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment