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

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 129ea1e6d783
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\Cmf\Component\Routing\RouteProviderInterface;
Chris@0 6 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
Chris@0 7 use Symfony\Component\HttpFoundation\Response;
Chris@0 8 use Symfony\Component\HttpKernel\Event\GetResponseEvent;
Chris@0 9 use Symfony\Component\HttpKernel\KernelEvents;
Chris@0 10 use Symfony\Component\Routing\Route;
Chris@0 11
Chris@0 12 /**
Chris@0 13 * Handles options requests.
Chris@0 14 *
Chris@0 15 * Therefore it sends a options response using all methods on all possible
Chris@0 16 * routes.
Chris@0 17 */
Chris@0 18 class OptionsRequestSubscriber implements EventSubscriberInterface {
Chris@0 19
Chris@0 20 /**
Chris@0 21 * The route provider.
Chris@0 22 *
Chris@0 23 * @var \Symfony\Cmf\Component\Routing\RouteProviderInterface
Chris@0 24 */
Chris@0 25 protected $routeProvider;
Chris@0 26
Chris@0 27 /**
Chris@0 28 * Creates a new OptionsRequestSubscriber instance.
Chris@0 29 *
Chris@0 30 * @param \Symfony\Cmf\Component\Routing\RouteProviderInterface $route_provider
Chris@0 31 * The route provider.
Chris@0 32 */
Chris@0 33 public function __construct(RouteProviderInterface $route_provider) {
Chris@0 34 $this->routeProvider = $route_provider;
Chris@0 35 }
Chris@0 36
Chris@0 37 /**
Chris@0 38 * Tries to handle the options request.
Chris@0 39 *
Chris@0 40 * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
Chris@0 41 * The request event.
Chris@0 42 */
Chris@0 43 public function onRequest(GetResponseEvent $event) {
Chris@0 44 if ($event->getRequest()->isMethod('OPTIONS')) {
Chris@0 45 $routes = $this->routeProvider->getRouteCollectionForRequest($event->getRequest());
Chris@0 46 // In case we don't have any routes, a 403 should be thrown by the normal
Chris@0 47 // request handling.
Chris@0 48 if (count($routes) > 0) {
Chris@0 49 // Flatten and unique the available methods.
Chris@17 50 $methods = array_reduce($routes->all(), function ($methods, Route $route) {
Chris@17 51 return array_merge($methods, $route->getMethods());
Chris@17 52 }, []);
Chris@17 53 $methods = array_unique($methods);
Chris@0 54 $response = new Response('', 200, ['Allow' => implode(', ', $methods)]);
Chris@0 55 $event->setResponse($response);
Chris@0 56 }
Chris@0 57 }
Chris@0 58 }
Chris@0 59
Chris@0 60 /**
Chris@0 61 * {@inheritdoc}
Chris@0 62 */
Chris@0 63 public static function getSubscribedEvents() {
Chris@0 64 // Set a high priority so it is executed before routing.
Chris@0 65 $events[KernelEvents::REQUEST][] = ['onRequest', 1000];
Chris@0 66 return $events;
Chris@0 67 }
Chris@0 68
Chris@0 69 }