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