RouteMethodSubscriber.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Drupal\Core\Routing\RouteBuildEvent;
  4. use Drupal\Core\Routing\RoutingEvents;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. /**
  7. * Provides a default value for the HTTP method restriction on routes.
  8. *
  9. * Most routes will only deal with GET and POST requests, so we restrict them to
  10. * those two if nothing else is specified. This is necessary to give other
  11. * routes a chance during the route matching process when they are listening
  12. * for example to DELETE requests on the same path. A typical use case are REST
  13. * web service routes that use the full spectrum of HTTP methods.
  14. */
  15. class RouteMethodSubscriber implements EventSubscriberInterface {
  16. /**
  17. * Sets a default value of GET|POST for the _method route property.
  18. *
  19. * @param \Drupal\Core\Routing\RouteBuildEvent $event
  20. * The event containing the build routes.
  21. */
  22. public function onRouteBuilding(RouteBuildEvent $event) {
  23. foreach ($event->getRouteCollection() as $route) {
  24. $methods = $route->getMethods();
  25. if (empty($methods)) {
  26. $route->setMethods(['GET', 'POST']);
  27. }
  28. }
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public static function getSubscribedEvents() {
  34. // Set a higher priority to ensure that routes get the default HTTP methods
  35. // as early as possible.
  36. $events[RoutingEvents::ALTER][] = ['onRouteBuilding', 5000];
  37. return $events;
  38. }
  39. }