annotate core/lib/Drupal/Core/EventSubscriber/RenderArrayNonHtmlSubscriber.php @ 19:fa3358dc1485 tip

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