protected function FinishResponseSubscriber::setResponseCacheable

protected FinishResponseSubscriber::setResponseCacheable(Response $response, Request $request)

Add Cache-Control and Expires headers to a cacheable response.

Parameters

\Symfony\Component\HttpFoundation\Response $response: A response object.

\Symfony\Component\HttpFoundation\Request $request: A request object.

File

core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php, line 221

Class

FinishResponseSubscriber
Response subscriber to handle finished responses.

Namespace

Drupal\Core\EventSubscriber

Code

protected function setResponseCacheable(Response $response, Request $request) {
  // HTTP/1.0 proxies do not support the Vary header, so prevent any caching
  // by sending an Expires date in the past. HTTP/1.1 clients ignore the
  // Expires header if a Cache-Control: max-age directive is specified (see
  // RFC 2616, section 14.9.3).
  if (!$response->headers->has('Expires')) {
    $this->setExpiresNoCache($response);
  }

  $max_age = $this->config->get('cache.page.max_age');
  $response->headers->set('Cache-Control', 'public, max-age=' . $max_age);

  // In order to support HTTP cache-revalidation, ensure that there is a
  // Last-Modified and an ETag header on the response.
  if (!$response->headers->has('Last-Modified')) {
    $timestamp = REQUEST_TIME;
    $response->setLastModified(new \DateTime(gmdate(DateTimePlus::RFC7231, REQUEST_TIME)));
  }
  else {
    $timestamp = $response->getLastModified()->getTimestamp();
  }
  $response->setEtag($timestamp);

  // Allow HTTP proxies to cache pages for anonymous users without a session
  // cookie. The Vary header is used to indicates the set of request-header
  // fields that fully determines whether a cache is permitted to use the
  // response to reply to a subsequent request for a given URL without
  // revalidation.
  if (!$response->hasVary() && !Settings::get('omit_vary_cookie')) {
    $response->setVary('Cookie', FALSE);
  }
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!EventSubscriber!FinishResponseSubscriber.php/function/FinishResponseSubscriber::setResponseCacheable/8.1.x