You are here

public function AnonymousUserResponseSubscriber::onRespond in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/lib/Drupal/Core/EventSubscriber/AnonymousUserResponseSubscriber.php \Drupal\Core\EventSubscriber\AnonymousUserResponseSubscriber::onRespond()

Adds a cache tag if the 'user.permissions' cache context is present.

Parameters

\Symfony\Component\HttpKernel\Event\FilterResponseEvent $event: The event to process.

File

core/lib/Drupal/Core/EventSubscriber/AnonymousUserResponseSubscriber.php, line 45
Contains \Drupal\Core\EventSubscriber\AnonymousUserResponseSubscriber.

Class

AnonymousUserResponseSubscriber
Response subscriber to handle finished responses for the anonymous user.

Namespace

Drupal\Core\EventSubscriber

Code

public function onRespond(FilterResponseEvent $event) {
  if (!$event
    ->isMasterRequest()) {
    return;
  }
  if (!$this->currentUser
    ->isAnonymous()) {
    return;
  }
  $response = $event
    ->getResponse();
  if (!$response instanceof CacheableResponseInterface) {
    return;
  }

  // The 'user.permissions' cache context ensures that if the permissions for
  // a role are modified, users are not served stale render cache content.
  // But, when entire responses are cached in reverse proxies, the value for
  // the cache context is never calculated, causing the stale response to not
  // be invalidated. Therefore, when varying by permissions and the current
  // user is the anonymous user, also add the cache tag for the 'anonymous'
  // role.
  if (in_array('user.permissions', $response
    ->getCacheableMetadata()
    ->getCacheContexts())) {
    $per_permissions_response_for_anon = new CacheableMetadata();
    $per_permissions_response_for_anon
      ->setCacheTags([
      'config:user.role.anonymous',
    ]);
    $response
      ->addCacheableDependency($per_permissions_response_for_anon);
  }
}