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 UrlMatcherInterfaceRequestMatcherInterface
  26. {
  27.     const REQUIREMENT_MATCH 0;
  28.     const REQUIREMENT_MISMATCH 1;
  29.     const ROUTE_MATCH 2;
  30.     protected $context;
  31.     /**
  32.      * Collects HTTP methods that would be allowed for the request.
  33.      */
  34.     protected $allow = array();
  35.     /**
  36.      * Collects URI schemes that would be allowed for the request.
  37.      *
  38.      * @internal
  39.      */
  40.     protected $allowSchemes = array();
  41.     protected $routes;
  42.     protected $request;
  43.     protected $expressionLanguage;
  44.     /**
  45.      * @var ExpressionFunctionProviderInterface[]
  46.      */
  47.     protected $expressionLanguageProviders = array();
  48.     public function __construct(RouteCollection $routesRequestContext $context)
  49.     {
  50.         $this->routes $routes;
  51.         $this->context $context;
  52.     }
  53.     /**
  54.      * {@inheritdoc}
  55.      */
  56.     public function setContext(RequestContext $context)
  57.     {
  58.         $this->context $context;
  59.     }
  60.     /**
  61.      * {@inheritdoc}
  62.      */
  63.     public function getContext()
  64.     {
  65.         return $this->context;
  66.     }
  67.     /**
  68.      * {@inheritdoc}
  69.      */
  70.     public function match($pathinfo)
  71.     {
  72.         $this->allow $this->allowSchemes = array();
  73.         if ($ret $this->matchCollection(rawurldecode($pathinfo) ?: '/'$this->routes)) {
  74.             return $ret;
  75.         }
  76.         if ('/' === $pathinfo && !$this->allow) {
  77.             throw new NoConfigurationException();
  78.         }
  79.         throw < \count($this->allow)
  80.             ? new MethodNotAllowedException(array_unique($this->allow))
  81.             : 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.      * @param RouteCollection $routes   The set of routes
  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.             if ($trimmedPathinfo === $pathinfo || !$hasTrailingVar preg_match('#\{\w+\}/?$#'$route->getPath())) {
  133.                 // no-op
  134.             } elseif (preg_match($regex$trimmedPathinfo$m)) {
  135.                 $matches $m;
  136.             } else {
  137.                 $hasTrailingSlash true;
  138.             }
  139.             if ('/' !== $pathinfo && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
  140.                 if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET'$requiredMethods))) {
  141.                     return $this->allow $this->allowSchemes = array();
  142.                 }
  143.                 if ($trimmedPathinfo === $pathinfo || !$hasTrailingVar) {
  144.                     continue;
  145.                 }
  146.             }
  147.             $hostMatches = array();
  148.             if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  149.                 continue;
  150.             }
  151.             $status $this->handleRouteRequirements($pathinfo$name$route);
  152.             if (self::REQUIREMENT_MISMATCH === $status[0]) {
  153.                 continue;
  154.             }
  155.             $hasRequiredScheme = !$route->getSchemes() || $route->hasScheme($this->context->getScheme());
  156.             if ($requiredMethods) {
  157.                 if (!\in_array($method$requiredMethods)) {
  158.                     if ($hasRequiredScheme) {
  159.                         $this->allow array_merge($this->allow$requiredMethods);
  160.                     }
  161.                     continue;
  162.                 }
  163.             }
  164.             if (!$hasRequiredScheme) {
  165.                 $this->allowSchemes array_merge($this->allowSchemes$route->getSchemes());
  166.                 continue;
  167.             }
  168.             return $this->getAttributes($route$namearray_replace($matches$hostMatches, isset($status[1]) ? $status[1] : array()));
  169.         }
  170.         return array();
  171.     }
  172.     /**
  173.      * Returns an array of values to use as request attributes.
  174.      *
  175.      * As this method requires the Route object, it is not available
  176.      * in matchers that do not have access to the matched Route instance
  177.      * (like the PHP and Apache matcher dumpers).
  178.      *
  179.      * @param Route  $route      The route we are matching against
  180.      * @param string $name       The name of the route
  181.      * @param array  $attributes An array of attributes from the matcher
  182.      *
  183.      * @return array An array of parameters
  184.      */
  185.     protected function getAttributes(Route $route$name, array $attributes)
  186.     {
  187.         $defaults $route->getDefaults();
  188.         if (isset($defaults['_canonical_route'])) {
  189.             $name $defaults['_canonical_route'];
  190.             unset($defaults['_canonical_route']);
  191.         }
  192.         $attributes['_route'] = $name;
  193.         return $this->mergeDefaults($attributes$defaults);
  194.     }
  195.     /**
  196.      * Handles specific route requirements.
  197.      *
  198.      * @param string $pathinfo The path
  199.      * @param string $name     The route name
  200.      * @param Route  $route    The route
  201.      *
  202.      * @return array The first element represents the status, the second contains additional information
  203.      */
  204.     protected function handleRouteRequirements($pathinfo$nameRoute $route)
  205.     {
  206.         // expression condition
  207.         if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context'request' => $this->request ?: $this->createRequest($pathinfo)))) {
  208.             return array(self::REQUIREMENT_MISMATCHnull);
  209.         }
  210.         return array(self::REQUIREMENT_MATCHnull);
  211.     }
  212.     /**
  213.      * Get merged default parameters.
  214.      *
  215.      * @param array $params   The parameters
  216.      * @param array $defaults The defaults
  217.      *
  218.      * @return array Merged default parameters
  219.      */
  220.     protected function mergeDefaults($params$defaults)
  221.     {
  222.         foreach ($params as $key => $value) {
  223.             if (!\is_int($key) && null !== $value) {
  224.                 $defaults[$key] = $value;
  225.             }
  226.         }
  227.         return $defaults;
  228.     }
  229.     protected function getExpressionLanguage()
  230.     {
  231.         if (null === $this->expressionLanguage) {
  232.             if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  233.                 throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  234.             }
  235.             $this->expressionLanguage = new ExpressionLanguage(null$this->expressionLanguageProviders);
  236.         }
  237.         return $this->expressionLanguage;
  238.     }
  239.     /**
  240.      * @internal
  241.      */
  242.     protected function createRequest($pathinfo)
  243.     {
  244.         if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
  245.             return null;
  246.         }
  247.         return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo$this->context->getMethod(), $this->context->getParameters(), array(), array(), array(
  248.             'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  249.             'SCRIPT_NAME' => $this->context->getBaseUrl(),
  250.         ));
  251.     }
  252. }