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

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\Routing\Exception\MethodNotAllowedException;
  12. use Symfony\Component\Routing\Exception\NoConfigurationException;
  13. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  14. use Symfony\Component\Routing\RouteCollection;
  15. use Symfony\Component\Routing\RequestContext;
  16. use Symfony\Component\Routing\Route;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
  19. use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
  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.     protected $allow = array();
  32.     protected $routes;
  33.     protected $request;
  34.     protected $expressionLanguage;
  35.     /**
  36.      * @var ExpressionFunctionProviderInterface[]
  37.      */
  38.     protected $expressionLanguageProviders = array();
  39.     public function __construct(RouteCollection $routesRequestContext $context)
  40.     {
  41.         $this->routes $routes;
  42.         $this->context $context;
  43.     }
  44.     /**
  45.      * {@inheritdoc}
  46.      */
  47.     public function setContext(RequestContext $context)
  48.     {
  49.         $this->context $context;
  50.     }
  51.     /**
  52.      * {@inheritdoc}
  53.      */
  54.     public function getContext()
  55.     {
  56.         return $this->context;
  57.     }
  58.     /**
  59.      * {@inheritdoc}
  60.      */
  61.     public function match($pathinfo)
  62.     {
  63.         $this->allow = array();
  64.         if ($ret $this->matchCollection(rawurldecode($pathinfo), $this->routes)) {
  65.             return $ret;
  66.         }
  67.         if ('/' === $pathinfo && !$this->allow) {
  68.             throw new NoConfigurationException();
  69.         }
  70.         throw count($this->allow)
  71.             ? new MethodNotAllowedException(array_unique($this->allow))
  72.             : new ResourceNotFoundException(sprintf('No routes found for "%s".'$pathinfo));
  73.     }
  74.     /**
  75.      * {@inheritdoc}
  76.      */
  77.     public function matchRequest(Request $request)
  78.     {
  79.         $this->request $request;
  80.         $ret $this->match($request->getPathInfo());
  81.         $this->request null;
  82.         return $ret;
  83.     }
  84.     public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  85.     {
  86.         $this->expressionLanguageProviders[] = $provider;
  87.     }
  88.     /**
  89.      * Tries to match a URL with a set of routes.
  90.      *
  91.      * @param string          $pathinfo The path info to be parsed
  92.      * @param RouteCollection $routes   The set of routes
  93.      *
  94.      * @return array An array of parameters
  95.      *
  96.      * @throws NoConfigurationException  If no routing configuration could be found
  97.      * @throws ResourceNotFoundException If the resource could not be found
  98.      * @throws MethodNotAllowedException If the resource was found but the request method is not allowed
  99.      */
  100.     protected function matchCollection($pathinfoRouteCollection $routes)
  101.     {
  102.         foreach ($routes as $name => $route) {
  103.             $compiledRoute $route->compile();
  104.             // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
  105.             if ('' !== $compiledRoute->getStaticPrefix() && !== strpos($pathinfo$compiledRoute->getStaticPrefix())) {
  106.                 continue;
  107.             }
  108.             if (!preg_match($compiledRoute->getRegex(), $pathinfo$matches)) {
  109.                 continue;
  110.             }
  111.             $hostMatches = array();
  112.             if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  113.                 continue;
  114.             }
  115.             $status $this->handleRouteRequirements($pathinfo$name$route);
  116.             if (self::REQUIREMENT_MISMATCH === $status[0]) {
  117.                 continue;
  118.             }
  119.             // check HTTP method requirement
  120.             if ($requiredMethods $route->getMethods()) {
  121.                 // HEAD and GET are equivalent as per RFC
  122.                 if ('HEAD' === $method $this->context->getMethod()) {
  123.                     $method 'GET';
  124.                 }
  125.                 if (!in_array($method$requiredMethods)) {
  126.                     if (self::REQUIREMENT_MATCH === $status[0]) {
  127.                         $this->allow array_merge($this->allow$requiredMethods);
  128.                     }
  129.                     continue;
  130.                 }
  131.             }
  132.             return $this->getAttributes($route$namearray_replace($matches$hostMatches, isset($status[1]) ? $status[1] : array()));
  133.         }
  134.     }
  135.     /**
  136.      * Returns an array of values to use as request attributes.
  137.      *
  138.      * As this method requires the Route object, it is not available
  139.      * in matchers that do not have access to the matched Route instance
  140.      * (like the PHP and Apache matcher dumpers).
  141.      *
  142.      * @param Route  $route      The route we are matching against
  143.      * @param string $name       The name of the route
  144.      * @param array  $attributes An array of attributes from the matcher
  145.      *
  146.      * @return array An array of parameters
  147.      */
  148.     protected function getAttributes(Route $route$name, array $attributes)
  149.     {
  150.         $attributes['_route'] = $name;
  151.         return $this->mergeDefaults($attributes$route->getDefaults());
  152.     }
  153.     /**
  154.      * Handles specific route requirements.
  155.      *
  156.      * @param string $pathinfo The path
  157.      * @param string $name     The route name
  158.      * @param Route  $route    The route
  159.      *
  160.      * @return array The first element represents the status, the second contains additional information
  161.      */
  162.     protected function handleRouteRequirements($pathinfo$nameRoute $route)
  163.     {
  164.         // expression condition
  165.         if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context'request' => $this->request ?: $this->createRequest($pathinfo)))) {
  166.             return array(self::REQUIREMENT_MISMATCHnull);
  167.         }
  168.         // check HTTP scheme requirement
  169.         $scheme $this->context->getScheme();
  170.         $status $route->getSchemes() && !$route->hasScheme($scheme) ? self::REQUIREMENT_MISMATCH self::REQUIREMENT_MATCH;
  171.         return array($statusnull);
  172.     }
  173.     /**
  174.      * Get merged default parameters.
  175.      *
  176.      * @param array $params   The parameters
  177.      * @param array $defaults The defaults
  178.      *
  179.      * @return array Merged default parameters
  180.      */
  181.     protected function mergeDefaults($params$defaults)
  182.     {
  183.         foreach ($params as $key => $value) {
  184.             if (!is_int($key)) {
  185.                 $defaults[$key] = $value;
  186.             }
  187.         }
  188.         return $defaults;
  189.     }
  190.     protected function getExpressionLanguage()
  191.     {
  192.         if (null === $this->expressionLanguage) {
  193.             if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  194.                 throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  195.             }
  196.             $this->expressionLanguage = new ExpressionLanguage(null$this->expressionLanguageProviders);
  197.         }
  198.         return $this->expressionLanguage;
  199.     }
  200.     /**
  201.      * @internal
  202.      */
  203.     protected function createRequest($pathinfo)
  204.     {
  205.         if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
  206.             return null;
  207.         }
  208.         return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo$this->context->getMethod(), $this->context->getParameters(), array(), array(), array(
  209.             'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  210.             'SCRIPT_NAME' => $this->context->getBaseUrl(),
  211.         ));
  212.     }
  213. }