You are here

class RouteMethodSubscriber in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/EventSubscriber/RouteMethodSubscriber.php \Drupal\Core\EventSubscriber\RouteMethodSubscriber
  2. 10 core/lib/Drupal/Core/EventSubscriber/RouteMethodSubscriber.php \Drupal\Core\EventSubscriber\RouteMethodSubscriber

Provides a default value for the HTTP method restriction on routes.

Most routes will only deal with GET and POST requests, so we restrict them to those two if nothing else is specified. This is necessary to give other routes a chance during the route matching process when they are listening for example to DELETE requests on the same path. A typical use case are REST web service routes that use the full spectrum of HTTP methods.

Hierarchy

  • class \Drupal\Core\EventSubscriber\RouteMethodSubscriber implements \Symfony\Component\EventDispatcher\EventSubscriberInterface

Expanded class hierarchy of RouteMethodSubscriber

1 string reference to 'RouteMethodSubscriber'
core.services.yml in core/core.services.yml
core/core.services.yml
1 service uses RouteMethodSubscriber
route_http_method_subscriber in core/core.services.yml
Drupal\Core\EventSubscriber\RouteMethodSubscriber

File

core/lib/Drupal/Core/EventSubscriber/RouteMethodSubscriber.php, line 18

Namespace

Drupal\Core\EventSubscriber
View source
class RouteMethodSubscriber implements EventSubscriberInterface {

  /**
   * Sets a default value of GET|POST for the _method route property.
   *
   * @param \Drupal\Core\Routing\RouteBuildEvent $event
   *   The event containing the build routes.
   */
  public function onRouteBuilding(RouteBuildEvent $event) {
    foreach ($event
      ->getRouteCollection() as $route) {
      $methods = $route
        ->getMethods();
      if (empty($methods)) {
        $route
          ->setMethods([
          'GET',
          'POST',
        ]);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {

    // Set a higher priority to ensure that routes get the default HTTP methods
    // as early as possible.
    $events[RoutingEvents::ALTER][] = [
      'onRouteBuilding',
      5000,
    ];
    return $events;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
RouteMethodSubscriber::getSubscribedEvents public static function Returns an array of event names this subscriber wants to listen to.
RouteMethodSubscriber::onRouteBuilding public function Sets a default value of GET|POST for the _method route property.