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

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