3 namespace Drupal\Core\EventSubscriber;
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;
13 * Handles options requests.
15 * Therefore it sends a options response using all methods on all possible
18 class OptionsRequestSubscriber implements EventSubscriberInterface {
23 * @var \Symfony\Cmf\Component\Routing\RouteProviderInterface
25 protected $routeProvider;
28 * Creates a new OptionsRequestSubscriber instance.
30 * @param \Symfony\Cmf\Component\Routing\RouteProviderInterface $route_provider
33 public function __construct(RouteProviderInterface $route_provider) {
34 $this->routeProvider = $route_provider;
38 * Tries to handle the options request.
40 * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
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
48 if (count($routes) > 0) {
49 $methods = array_map(function (Route $route) {
50 return $route->getMethods();
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);
63 public static function getSubscribedEvents() {
64 // Set a high priority so it is executed before routing.
65 $events[KernelEvents::REQUEST][] = ['onRequest', 1000];