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

Open in your IDE?
  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 $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.     /**
  55.      * {@inheritdoc}
  56.      */
  57.     public function setContext(RequestContext $context)
  58.     {
  59.         $this->context = $context;
  60.     }
  61.     /**
  62.      * {@inheritdoc}
  63.      */
  64.     public function getContext()
  65.     {
  66.         return $this->context;
  67.     }
  68.     /**
  69.      * {@inheritdoc}
  70.      */
  71.     public function match(string $pathinfo)
  72.     {
  73.         $this->allow = $this->allowSchemes = [];
  74.         $pathinfo = '' === ($pathinfo = rawurldecode($pathinfo)) ? '/' : $pathinfo;
  75.         if ($ret = $this->matchCollection($pathinfo, $this->routes)) {
  76.             return $ret;
  77.         }
  78.         if ('/' === $pathinfo && !$this->allow && !$this->allowSchemes) {
  79.             throw new NoConfigurationException();
  80.         }
  81.         throw 0 < \count($this->allow) ? new MethodNotAllowedException(array_unique($this->allow)) : new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
  82.     }
  83.     /**
  84.      * {@inheritdoc}
  85.      */
  86.     public function matchRequest(Request $request)
  87.     {
  88.         $this->request = $request;
  89.         $ret = $this->match($request->getPathInfo());
  90.         $this->request = null;
  91.         return $ret;
  92.     }
  93.     public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  94.     {
  95.         $this->expressionLanguageProviders[] = $provider;
  96.     }
  97.     /**
  98.      * Tries to match a URL with a set of routes.
  99.      *
  100.      * @param string $pathinfo The path info to be parsed
  101.      *
  102.      * @return array
  103.      *
  104.      * @throws NoConfigurationException  If no routing configuration could be found
  105.      * @throws ResourceNotFoundException If the resource could not be found
  106.      * @throws MethodNotAllowedException If the resource was found but the request method is not allowed
  107.      */
  108.     protected function matchCollection(string $pathinfo, RouteCollection $routes)
  109.     {
  110.         // HEAD and GET are equivalent as per RFC
  111.         if ('HEAD' === $method = $this->context->getMethod()) {
  112.             $method = 'GET';
  113.         }
  114.         $supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface;
  115.         $trimmedPathinfo = '' === ($trimmedPathinfo = rtrim($pathinfo, '/')) ? '/' : $trimmedPathinfo;
  116.         foreach ($routes as $name => $route) {
  117.             $compiledRoute = $route->compile();
  118.             $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
  119.             $requiredMethods = $route->getMethods();
  120.             // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
  121.             if ('' !== $staticPrefix && !str_starts_with($trimmedPathinfo, $staticPrefix)) {
  122.                 continue;
  123.             }
  124.             $regex = $compiledRoute->getRegex();
  125.             $pos = strrpos($regex, '$');
  126.             $hasTrailingSlash = '/' === $regex[$pos - 1];
  127.             $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
  128.             if (!preg_match($regex, $pathinfo, $matches)) {
  129.                 continue;
  130.             }
  131.             $hasTrailingVar = $trimmedPathinfo !== $pathinfo && preg_match('#\{\w+\}/?$#', $route->getPath());
  132.             if ($hasTrailingVar && ($hasTrailingSlash || (null === $m = $matches[\count($compiledRoute->getPathVariables())] ?? null) || '/' !== ($m[-1] ?? '/')) && preg_match($regex, $trimmedPathinfo, $m)) {
  133.                 if ($hasTrailingSlash) {
  134.                     $matches = $m;
  135.                 } else {
  136.                     $hasTrailingVar = false;
  137.                 }
  138.             }
  139.             $hostMatches = [];
  140.             if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  141.                 continue;
  142.             }
  143.             $status = $this->handleRouteRequirements($pathinfo, $name, $route);
  144.             if (self::REQUIREMENT_MISMATCH === $status[0]) {
  145.                 continue;
  146.             }
  147.             if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
  148.                 if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) {
  149.                     return $this->allow = $this->allowSchemes = [];
  150.                 }
  151.                 continue;
  152.             }
  153.             if ($route->getSchemes() && !$route->hasScheme($this->context->getScheme())) {
  154.                 $this->allowSchemes = array_merge($this->allowSchemes, $route->getSchemes());
  155.                 continue;
  156.             }
  157.             if ($requiredMethods && !\in_array($method, $requiredMethods)) {
  158.                 $this->allow = array_merge($this->allow, $requiredMethods);
  159.                 continue;
  160.             }
  161.             return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, $status[1] ?? []));
  162.         }
  163.         return [];
  164.     }
  165.     /**
  166.      * Returns an array of values to use as request attributes.
  167.      *
  168.      * As this method requires the Route object, it is not available
  169.      * in matchers that do not have access to the matched Route instance
  170.      * (like the PHP and Apache matcher dumpers).
  171.      *
  172.      * @return array
  173.      */
  174.     protected function getAttributes(Route $route, string $name, array $attributes)
  175.     {
  176.         $defaults = $route->getDefaults();
  177.         if (isset($defaults['_canonical_route'])) {
  178.             $name = $defaults['_canonical_route'];
  179.             unset($defaults['_canonical_route']);
  180.         }
  181.         $attributes['_route'] = $name;
  182.         return $this->mergeDefaults($attributes, $defaults);
  183.     }
  184.     /**
  185.      * Handles specific route requirements.
  186.      *
  187.      * @return array The first element represents the status, the second contains additional information
  188.      */
  189.     protected function handleRouteRequirements(string $pathinfo, string $name, Route $route)
  190.     {
  191.         // expression condition
  192.         if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), ['context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)])) {
  193.             return [self::REQUIREMENT_MISMATCH, null];
  194.         }
  195.         return [self::REQUIREMENT_MATCH, null];
  196.     }
  197.     /**
  198.      * Get merged default parameters.
  199.      *
  200.      * @return array
  201.      */
  202.     protected function mergeDefaults(array $params, array $defaults)
  203.     {
  204.         foreach ($params as $key => $value) {
  205.             if (!\is_int($key) && null !== $value) {
  206.                 $defaults[$key] = $value;
  207.             }
  208.         }
  209.         return $defaults;
  210.     }
  211.     protected function getExpressionLanguage()
  212.     {
  213.         if (null === $this->expressionLanguage) {
  214.             if (!class_exists(ExpressionLanguage::class)) {
  215.                 throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  216.             }
  217.             $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  218.         }
  219.         return $this->expressionLanguage;
  220.     }
  221.     /**
  222.      * @internal
  223.      */
  224.     protected function createRequest(string $pathinfo): ?Request
  225.     {
  226.         if (!class_exists(Request::class)) {
  227.             return null;
  228.         }
  229.         return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), [], [], [
  230.             'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  231.             'SCRIPT_NAME' => $this->context->getBaseUrl(),
  232.         ]);
  233.     }
  234. }