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