MethodFilter.php 1.4 KB

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