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

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 129ea1e6d783
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
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 $methods = array_map(function (Route $route) {
50 return $route->getMethods();
51 }, $routes->all());
52 // Flatten and unique the available methods.
53 $methods = array_unique(call_user_func_array('array_merge', $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 }