comparison core/lib/Drupal/Core/EventSubscriber/RenderArrayNonHtmlSubscriber.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\Core\EventSubscriber;
4
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;
9
10 /**
11 * Throws 406 if requesting non-HTML format and controller returns render array.
12 */
13 class RenderArrayNonHtmlSubscriber implements EventSubscriberInterface {
14
15 /**
16 * Throws an HTTP 406 error if client requested a non-HTML format.
17 *
18 * @param \Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent $event
19 * The event to process.
20 */
21 public function onRespond(GetResponseForControllerResultEvent $event) {
22 $request = $event->getRequest();
23 $result = $event->getControllerResult();
24
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());
31 }
32 }
33
34 /**
35 * {@inheritdoc}
36 */
37 public static function getSubscribedEvents() {
38 $events[KernelEvents::VIEW][] = ['onRespond', -10];
39 return $events;
40 }
41
42 }