3 namespace Drupal\Core\EventSubscriber;
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Cache\CacheableResponseInterface;
7 use Drupal\Core\Session\AccountInterface;
8 use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
9 use Symfony\Component\HttpKernel\KernelEvents;
10 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
13 * Response subscriber to handle finished responses for the anonymous user.
15 class AnonymousUserResponseSubscriber implements EventSubscriberInterface {
20 * @var \Drupal\Core\Session\AccountInterface
22 protected $currentUser;
25 * Constructs an AnonymousUserResponseSubscriber object.
27 * @param \Drupal\Core\Session\AccountInterface $current_user
30 public function __construct(AccountInterface $current_user) {
31 $this->currentUser = $current_user;
35 * Adds a cache tag if the 'user.permissions' cache context is present.
37 * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
38 * The event to process.
40 public function onRespond(FilterResponseEvent $event) {
41 if (!$event->isMasterRequest()) {
45 if (!$this->currentUser->isAnonymous()) {
49 $response = $event->getResponse();
50 if (!$response instanceof CacheableResponseInterface) {
54 // The 'user.permissions' cache context ensures that if the permissions for
55 // a role are modified, users are not served stale render cache content.
56 // But, when entire responses are cached in reverse proxies, the value for
57 // the cache context is never calculated, causing the stale response to not
58 // be invalidated. Therefore, when varying by permissions and the current
59 // user is the anonymous user, also add the cache tag for the 'anonymous'
61 if (in_array('user.permissions', $response->getCacheableMetadata()->getCacheContexts())) {
62 $per_permissions_response_for_anon = new CacheableMetadata();
63 $per_permissions_response_for_anon->setCacheTags(['config:user.role.anonymous']);
64 $response->addCacheableDependency($per_permissions_response_for_anon);
69 * Registers the methods in this class that should be listeners.
72 * An array of event listener definitions.
74 public static function getSubscribedEvents() {
75 // Priority 5, so that it runs before FinishResponseSubscriber, but after
76 // event subscribers that add the associated cacheability metadata (which
77 // have priority 10). This one is conditional, so must run after those.
78 $events[KernelEvents::RESPONSE][] = ['onRespond', 5];