You are here

protected function FinishResponseSubscriber::setResponseCacheable in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php \Drupal\Core\EventSubscriber\FinishResponseSubscriber::setResponseCacheable()
  2. 9 core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php \Drupal\Core\EventSubscriber\FinishResponseSubscriber::setResponseCacheable()

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 250

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);
  }
}