RenderArrayNonHtmlSubscriber.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
  5. use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. /**
  8. * Throws 406 if requesting non-HTML format and controller returns render array.
  9. */
  10. class RenderArrayNonHtmlSubscriber implements EventSubscriberInterface {
  11. /**
  12. * Throws an HTTP 406 error if client requested a non-HTML format.
  13. *
  14. * @param \Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent $event
  15. * The event to process.
  16. */
  17. public function onRespond(GetResponseForControllerResultEvent $event) {
  18. $request = $event->getRequest();
  19. $result = $event->getControllerResult();
  20. // If this is a render array then we assume that the router went with the
  21. // generic controller and not one with a format. If the format requested is
  22. // not HTML though, we can also assume that the requested format is invalid
  23. // so we provide a 406 response.
  24. if (is_array($result) && $request->getRequestFormat() !== 'html') {
  25. throw new NotAcceptableHttpException('Not acceptable format: ' . $request->getRequestFormat());
  26. }
  27. }
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public static function getSubscribedEvents() {
  32. $events[KernelEvents::VIEW][] = ['onRespond', -10];
  33. return $events;
  34. }
  35. }