3 namespace Drupal\Core\EventSubscriber;
5 use Drupal\Core\Cache\CacheableResponseInterface;
6 use Drupal\Core\Routing\AccessAwareRouterInterface;
7 use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
8 use Symfony\Component\HttpKernel\KernelEvents;
9 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
12 * Response subscriber to bubble the route's access result's cacheability.
14 * During routing, access checking is performed. The corresponding access result
15 * is stored in the Request object's attributes, just like the matching route
16 * object is. In case of a cacheable response, the route's access result also
17 * determined the content of the response, and therefore the cacheability of the
18 * route's access result should also be applied to the resulting response.
20 * @see \Drupal\Core\Routing\AccessAwareRouterInterface::ACCESS_RESULT
21 * @see \Drupal\Core\Routing\AccessAwareRouter::matchRequest()
22 * @see \Drupal\Core\Routing\AccessAwareRouter::checkAccess()
24 class RouteAccessResponseSubscriber implements EventSubscriberInterface {
27 * Bubbles the route's access result' cacheability metadata.
29 * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
30 * The event to process.
32 public function onRespond(FilterResponseEvent $event) {
33 if (!$event->isMasterRequest()) {
37 $response = $event->getResponse();
38 if (!$response instanceof CacheableResponseInterface) {
42 $request = $event->getRequest();
43 $access_result = $request->attributes->get(AccessAwareRouterInterface::ACCESS_RESULT);
44 $response->addCacheableDependency($access_result);
50 public static function getSubscribedEvents() {
51 // Priority 10, so that it runs before FinishResponseSubscriber, which will
52 // expose the cacheability metadata in the form of headers.
53 $events[KernelEvents::RESPONSE][] = ['onRespond', 10];