ClientErrorResponseSubscriber.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Drupal\Core\Cache\CacheableMetadata;
  4. use Drupal\Core\Cache\CacheableResponseInterface;
  5. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. /**
  9. * Response subscriber to set the '4xx-response' cache tag on 4xx responses.
  10. */
  11. class ClientErrorResponseSubscriber implements EventSubscriberInterface {
  12. /**
  13. * Sets the '4xx-response' cache tag on 4xx responses.
  14. *
  15. * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
  16. * The event to process.
  17. */
  18. public function onRespond(FilterResponseEvent $event) {
  19. if (!$event->isMasterRequest()) {
  20. return;
  21. }
  22. $response = $event->getResponse();
  23. if (!$response instanceof CacheableResponseInterface) {
  24. return;
  25. }
  26. if ($response->isClientError()) {
  27. $http_4xx_response_cacheability = new CacheableMetadata();
  28. $http_4xx_response_cacheability->setCacheTags(['4xx-response']);
  29. $response->addCacheableDependency($http_4xx_response_cacheability);
  30. }
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public static function getSubscribedEvents() {
  36. // Priority 10, so that it runs before FinishResponseSubscriber, which will
  37. // expose the cacheability metadata in the form of headers.
  38. $events[KernelEvents::RESPONSE][] = ['onRespond', 10];
  39. return $events;
  40. }
  41. }