vendor/symfony/routing/Matcher/UrlMatcher.php line 94

  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Routing\Matcher;
  11. use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
  12. use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  15. use Symfony\Component\Routing\Exception\NoConfigurationException;
  16. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  17. use Symfony\Component\Routing\RequestContext;
  18. use Symfony\Component\Routing\Route;
  19. use Symfony\Component\Routing\RouteCollection;
  20. /**
  21.  * UrlMatcher matches URL based on a set of routes.
  22.  *
  23.  * @author Fabien Potencier <fabien@symfony.com>
  24.  */
  25. class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
  26. {
  27.     public const REQUIREMENT_MATCH = 0;
  28.     public const REQUIREMENT_MISMATCH = 1;
  29.     public const ROUTE_MATCH = 2;
  30.     /** @var RequestContext */
  31.     protected $context;
  32.     /**
  33.      * Collects HTTP methods that would be allowed for the request.
  34.      */
  35.     protected $allow = [];
  36.     /**
  37.      * Collects URI schemes that would be allowed for the request.
  38.      *
  39.      * @internal
  40.      */
  41.     protected array $allowSchemes = [];
  42.     protected $routes;
  43.     protected $request;
  44.     protected $expressionLanguage;
  45.     /**
  46.      * @var ExpressionFunctionProviderInterface[]
  47.      */
  48.     protected $expressionLanguageProviders = [];
  49.     public function __construct(RouteCollection $routes, RequestContext $context)
  50.     {
  51.         $this->routes = $routes;
  52.         $this->context = $context;
  53.     }
  54.     public function setContext(RequestContext $context)
  55.     {
  56.         $this->context = $context;
  57.     }
  58.     public function getContext(): RequestContext
  59.     {
  60.         return $this->context;
  61.     }
  62.     public function match(string $pathinfo): array
  63.     {
  64.         $this->allow = $this->allowSchemes = [];
  65.         if ($ret = $this->matchCollection(rawurldecode($pathinfo) ?: '/', $this->routes)) {
  66.             return $ret;
  67.         }
  68.         if ('/' === $pathinfo && !$this->allow && !$this->allowSchemes) {
  69.             throw new NoConfigurationException();
  70.         }
  71.         throw 0 < \count($this->allow) ? new MethodNotAllowedException(array_unique($this->allow)) : new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
  72.     }
  73.     public function matchRequest(Request $request): array
  74.     {
  75.         $this->request = $request;
  76.         $ret = $this->match($request->getPathInfo());
  77.         $this->request = null;
  78.         return $ret;
  79.     }
  80.     public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  81.     {
  82.         $this->expressionLanguageProviders[] = $provider;
  83.     }
  84.     /**
  85.      * Tries to match a URL with a set of routes.
  86.      *
  87.      * @param string $pathinfo The path info to be parsed
  88.      *
  89.      * @throws NoConfigurationException  If no routing configuration could be found
  90.      * @throws ResourceNotFoundException If the resource could not be found
  91.      * @throws MethodNotAllowedException If the resource was found but the request method is not allowed
  92.      */
  93.     protected function matchCollection(string $pathinfo, RouteCollection $routes): array
  94.     {
  95.         // HEAD and GET are equivalent as per RFC
  96.         if ('HEAD' === $method = $this->context->getMethod()) {
  97.             $method = 'GET';
  98.         }
  99.         $supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface;
  100.         $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/';
  101.         foreach ($routes as $name => $route) {
  102.             $compiledRoute = $route->compile();
  103.             $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
  104.             $requiredMethods = $route->getMethods();
  105.             // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
  106.             if ('' !== $staticPrefix && !str_starts_with($trimmedPathinfo, $staticPrefix)) {
  107.                 continue;
  108.             }
  109.             $regex = $compiledRoute->getRegex();
  110.             $pos = strrpos($regex, '$');
  111.             $hasTrailingSlash = '/' === $regex[$pos - 1];
  112.             $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
  113.             if (!preg_match($regex, $pathinfo, $matches)) {
  114.                 continue;
  115.             }
  116.             $hasTrailingVar = $trimmedPathinfo !== $pathinfo && preg_match('#\{[\w\x80-\xFF]+\}/?$#', $route->getPath());
  117.             if ($hasTrailingVar && ($hasTrailingSlash || (null === $m = $matches[\count($compiledRoute->getPathVariables())] ?? null) || '/' !== ($m[-1] ?? '/')) && preg_match($regex, $trimmedPathinfo, $m)) {
  118.                 if ($hasTrailingSlash) {
  119.                     $matches = $m;
  120.                 } else {
  121.                     $hasTrailingVar = false;
  122.                 }
  123.             }
  124.             $hostMatches = [];
  125.             if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  126.                 continue;
  127.             }
  128.             $attributes = $this->getAttributes($route, $name, array_replace($matches, $hostMatches));
  129.             $status = $this->handleRouteRequirements($pathinfo, $name, $route, $attributes);
  130.             if (self::REQUIREMENT_MISMATCH === $status[0]) {
  131.                 continue;
  132.             }
  133.             if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
  134.                 if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) {
  135.                     return $this->allow = $this->allowSchemes = [];
  136.                 }
  137.                 continue;
  138.             }
  139.             if ($route->getSchemes() && !$route->hasScheme($this->context->getScheme())) {
  140.                 $this->allowSchemes = array_merge($this->allowSchemes, $route->getSchemes());
  141.                 continue;
  142.             }
  143.             if ($requiredMethods && !\in_array($method, $requiredMethods)) {
  144.                 $this->allow = array_merge($this->allow, $requiredMethods);
  145.                 continue;
  146.             }
  147.             return array_replace($attributes, $status[1] ?? []);
  148.         }
  149.         return [];
  150.     }
  151.     /**
  152.      * Returns an array of values to use as request attributes.
  153.      *
  154.      * As this method requires the Route object, it is not available
  155.      * in matchers that do not have access to the matched Route instance
  156.      * (like the PHP and Apache matcher dumpers).
  157.      */
  158.     protected function getAttributes(Route $route, string $name, array $attributes): array
  159.     {
  160.         $defaults = $route->getDefaults();
  161.         if (isset($defaults['_canonical_route'])) {
  162.             $name = $defaults['_canonical_route'];
  163.             unset($defaults['_canonical_route']);
  164.         }
  165.         $attributes['_route'] = $name;
  166.         return $this->mergeDefaults($attributes, $defaults);
  167.     }
  168.     /**
  169.      * Handles specific route requirements.
  170.      *
  171.      * @return array The first element represents the status, the second contains additional information
  172.      */
  173.     protected function handleRouteRequirements(string $pathinfo, string $name, Route $route/* , array $routeParameters */): array
  174.     {
  175.         if (\func_num_args() < 4) {
  176.             trigger_deprecation('symfony/routing', '6.1', 'The "%s()" method will have a new "array $routeParameters" argument in version 7.0, not defining it is deprecated.', __METHOD__);
  177.             $routeParameters = [];
  178.         } else {
  179.             $routeParameters = func_get_arg(3);
  180.             if (!\is_array($routeParameters)) {
  181.                 throw new \TypeError(sprintf('"%s": Argument $routeParameters is expected to be an array, got "%s".', __METHOD__, get_debug_type($routeParameters)));
  182.             }
  183.         }
  184.         // expression condition
  185.         if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), [
  186.             'context' => $this->context,
  187.             'request' => $this->request ?: $this->createRequest($pathinfo),
  188.             'params' => $routeParameters,
  189.         ])) {
  190.             return [self::REQUIREMENT_MISMATCH, null];
  191.         }
  192.         return [self::REQUIREMENT_MATCH, null];
  193.     }
  194.     /**
  195.      * Get merged default parameters.
  196.      */
  197.     protected function mergeDefaults(array $params, array $defaults): array
  198.     {
  199.         foreach ($params as $key => $value) {
  200.             if (!\is_int($key) && null !== $value) {
  201.                 $defaults[$key] = $value;
  202.             }
  203.         }
  204.         return $defaults;
  205.     }
  206.     protected function getExpressionLanguage()
  207.     {
  208.         if (null === $this->expressionLanguage) {
  209.             if (!class_exists(ExpressionLanguage::class)) {
  210.                 throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  211.             }
  212.             $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  213.         }
  214.         return $this->expressionLanguage;
  215.     }
  216.     /**
  217.      * @internal
  218.      */
  219.     protected function createRequest(string $pathinfo): ?Request
  220.     {
  221.         if (!class_exists(Request::class)) {
  222.             return null;
  223.         }
  224.         return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), [], [], [
  225.             'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  226.             'SCRIPT_NAME' => $this->context->getBaseUrl(),
  227.         ]);
  228.     }
  229. }