You are here

public function OptionsRequestSubscriber::onRequest in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/EventSubscriber/OptionsRequestSubscriber.php \Drupal\Core\EventSubscriber\OptionsRequestSubscriber::onRequest()

Tries to handle the options request.

Parameters

\Symfony\Component\HttpKernel\Event\GetResponseEvent $event: The request event.

File

core/lib/Drupal/Core/EventSubscriber/OptionsRequestSubscriber.php, line 43

Class

OptionsRequestSubscriber
Handles options requests.

Namespace

Drupal\Core\EventSubscriber

Code

public function onRequest(GetResponseEvent $event) {
  if ($event
    ->getRequest()
    ->isMethod('OPTIONS')) {
    $routes = $this->routeProvider
      ->getRouteCollectionForRequest($event
      ->getRequest());

    // In case we don't have any routes, a 403 should be thrown by the normal
    // request handling.
    if (count($routes) > 0) {

      // Flatten and unique the available methods.
      $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);
    }
  }
}