OptionsRequestSubscriber.php in Drupal 8
File
core/lib/Drupal/Core/EventSubscriber/OptionsRequestSubscriber.php
View source
<?php
namespace Drupal\Core\EventSubscriber;
use Symfony\Cmf\Component\Routing\RouteProviderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Route;
class OptionsRequestSubscriber implements EventSubscriberInterface {
protected $routeProvider;
public function __construct(RouteProviderInterface $route_provider) {
$this->routeProvider = $route_provider;
}
public function onRequest(GetResponseEvent $event) {
if ($event
->getRequest()
->isMethod('OPTIONS')) {
$routes = $this->routeProvider
->getRouteCollectionForRequest($event
->getRequest());
if (count($routes) > 0) {
$methods = array_reduce($routes
->all(), function ($methods, Route $route) {
return array_merge($methods, $route
->getMethods());
}, []);
$methods = array_unique($methods);
$response = new Response('', 200, [
'Allow' => implode(', ', $methods),
]);
$event
->setResponse($response);
}
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = [
'onRequest',
1000,
];
return $events;
}
}