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