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.         foreach ($routes as $name => $route) {
  112.             $compiledRoute $route->compile();
  113.             // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
  114.             if ('' !== $compiledRoute->getStaticPrefix() && !== strpos($pathinfo$compiledRoute->getStaticPrefix())) {
  115.                 continue;
  116.             }
  117.             if (!preg_match($compiledRoute->getRegex(), $pathinfo$matches)) {
  118.                 continue;
  119.             }
  120.             $hostMatches = array();
  121.             if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  122.                 continue;
  123.             }
  124.             $status $this->handleRouteRequirements($pathinfo$name$route);
  125.             if (self::REQUIREMENT_MISMATCH === $status[0]) {
  126.                 continue;
  127.             }
  128.             $hasRequiredScheme = !$route->getSchemes() || $route->hasScheme($this->context->getScheme());
  129.             if ($requiredMethods $route->getMethods()) {
  130.                 // HEAD and GET are equivalent as per RFC
  131.                 if ('HEAD' === $method $this->context->getMethod()) {
  132.                     $method 'GET';
  133.                 }
  134.                 if (!\in_array($method$requiredMethods)) {
  135.                     if ($hasRequiredScheme) {
  136.                         $this->allow array_merge($this->allow$requiredMethods);
  137.                     }
  138.                     continue;
  139.                 }
  140.             }
  141.             if (!$hasRequiredScheme) {
  142.                 $this->allowSchemes array_merge($this->allowSchemes$route->getSchemes());
  143.                 continue;
  144.             }
  145.             return $this->getAttributes($route$namearray_replace($matches$hostMatches, isset($status[1]) ? $status[1] : array()));
  146.         }
  147.     }
  148.     /**
  149.      * Returns an array of values to use as request attributes.
  150.      *
  151.      * As this method requires the Route object, it is not available
  152.      * in matchers that do not have access to the matched Route instance
  153.      * (like the PHP and Apache matcher dumpers).
  154.      *
  155.      * @param Route  $route      The route we are matching against
  156.      * @param string $name       The name of the route
  157.      * @param array  $attributes An array of attributes from the matcher
  158.      *
  159.      * @return array An array of parameters
  160.      */
  161.     protected function getAttributes(Route $route$name, array $attributes)
  162.     {
  163.         $defaults $route->getDefaults();
  164.         if (isset($defaults['_canonical_route'])) {
  165.             $name $defaults['_canonical_route'];
  166.             unset($defaults['_canonical_route']);
  167.         }
  168.         $attributes['_route'] = $name;
  169.         return $this->mergeDefaults($attributes$defaults);
  170.     }
  171.     /**
  172.      * Handles specific route requirements.
  173.      *
  174.      * @param string $pathinfo The path
  175.      * @param string $name     The route name
  176.      * @param Route  $route    The route
  177.      *
  178.      * @return array The first element represents the status, the second contains additional information
  179.      */
  180.     protected function handleRouteRequirements($pathinfo$nameRoute $route)
  181.     {
  182.         // expression condition
  183.         if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context'request' => $this->request ?: $this->createRequest($pathinfo)))) {
  184.             return array(self::REQUIREMENT_MISMATCHnull);
  185.         }
  186.         return array(self::REQUIREMENT_MATCHnull);
  187.     }
  188.     /**
  189.      * Get merged default parameters.
  190.      *
  191.      * @param array $params   The parameters
  192.      * @param array $defaults The defaults
  193.      *
  194.      * @return array Merged default parameters
  195.      */
  196.     protected function mergeDefaults($params$defaults)
  197.     {
  198.         foreach ($params as $key => $value) {
  199.             if (!\is_int($key) && null !== $value) {
  200.                 $defaults[$key] = $value;
  201.             }
  202.         }
  203.         return $defaults;
  204.     }
  205.     protected function getExpressionLanguage()
  206.     {
  207.         if (null === $this->expressionLanguage) {
  208.             if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  209.                 throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  210.             }
  211.             $this->expressionLanguage = new ExpressionLanguage(null$this->expressionLanguageProviders);
  212.         }
  213.         return $this->expressionLanguage;
  214.     }
  215.     /**
  216.      * @internal
  217.      */
  218.     protected function createRequest($pathinfo)
  219.     {
  220.         if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
  221.             return null;
  222.         }
  223.         return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo$this->context->getMethod(), $this->context->getParameters(), array(), array(), array(
  224.             'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  225.             'SCRIPT_NAME' => $this->context->getBaseUrl(),
  226.         ));
  227.     }
  228. }