OptionsRequestSubscriber.php in Drupal 9
File
core/lib/Drupal/Core/EventSubscriber/OptionsRequestSubscriber.php
View source
<?php
namespace Drupal\Core\EventSubscriber;
use Drupal\Core\Routing\RouteProviderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
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(RequestEvent $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;
}
}