e565a3e0cf31b8aa40528cefcb182ebe8035dcc1
[yaffs-website] / web / core / lib / Drupal / Core / Routing / MethodFilter.php
1 <?php
2
3 namespace Drupal\Core\Routing;
4
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;
9
10 /**
11  * Filters routes based on the HTTP method.
12  */
13 class MethodFilter implements RouteFilterInterface {
14
15   /**
16    * {@inheritdoc}
17    */
18   public function filter(RouteCollection $collection, Request $request) {
19     $method = $request->getMethod();
20
21     $all_supported_methods = [];
22
23     foreach ($collection->all() as $name => $route) {
24       $supported_methods = $route->getMethods();
25
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)) {
30         continue;
31       }
32
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';
37       }
38
39       if (!in_array($method, $supported_methods, TRUE)) {
40         $all_supported_methods = array_merge($supported_methods, $all_supported_methods);
41         $collection->remove($name);
42       }
43     }
44     if (count($collection)) {
45       return $collection;
46     }
47     throw new MethodNotAllowedException(array_unique($all_supported_methods));
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   public function applies(Route $route) {
54     return !empty($route->getMethods());
55   }
56
57 }