3 namespace Drupal\Core\Routing;
5 use Symfony\Component\HttpFoundation\Request;
6 use Symfony\Component\Routing\Exception\MethodNotAllowedException;
7 use Symfony\Component\Routing\Route;
8 use Symfony\Component\Routing\RouteCollection;
11 * Filters routes based on the HTTP method.
13 class MethodFilter implements RouteFilterInterface {
18 public function filter(RouteCollection $collection, Request $request) {
19 $method = $request->getMethod();
21 $all_supported_methods = [];
23 foreach ($collection->all() as $name => $route) {
24 $supported_methods = $route->getMethods();
26 // A route not restricted to specific methods allows any method. If this
27 // is the case, we'll also have at least one route left in the collection,
28 // hence we don't need to calculate the set of all supported methods.
29 if (empty($supported_methods)) {
33 // If the GET method is allowed we also need to allow the HEAD method
34 // since HEAD is a GET method that doesn't return the body.
35 if (in_array('GET', $supported_methods, TRUE)) {
36 $supported_methods[] = 'HEAD';
39 if (!in_array($method, $supported_methods, TRUE)) {
40 $all_supported_methods = array_merge($supported_methods, $all_supported_methods);
41 $collection->remove($name);
44 if (count($collection)) {
47 throw new MethodNotAllowedException(array_unique($all_supported_methods));
53 public function applies(Route $route) {
54 return !empty($route->getMethods());