UrlMatcher.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. 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 = [];
  35. /**
  36. * Collects URI schemes that would be allowed for the request.
  37. *
  38. * @internal
  39. */
  40. protected $allowSchemes = [];
  41. protected $routes;
  42. protected $request;
  43. protected $expressionLanguage;
  44. /**
  45. * @var ExpressionFunctionProviderInterface[]
  46. */
  47. protected $expressionLanguageProviders = [];
  48. public function __construct(RouteCollection $routes, RequestContext $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 = [];
  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 0 < \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($pathinfo, RouteCollection $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 && 0 !== 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, 1 + $hasTrailingSlash);
  129. if (!preg_match($regex, $pathinfo, $matches)) {
  130. continue;
  131. }
  132. $hasTrailingVar = $trimmedPathinfo !== $pathinfo && preg_match('#\{\w+\}/?$#', $route->getPath());
  133. if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
  134. if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) {
  135. return $this->allow = $this->allowSchemes = [];
  136. }
  137. continue;
  138. }
  139. if ($hasTrailingSlash && $hasTrailingVar && preg_match($regex, $trimmedPathinfo, $m)) {
  140. $matches = $m;
  141. }
  142. $hostMatches = [];
  143. if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  144. continue;
  145. }
  146. $status = $this->handleRouteRequirements($pathinfo, $name, $route);
  147. if (self::REQUIREMENT_MISMATCH === $status[0]) {
  148. continue;
  149. }
  150. $hasRequiredScheme = !$route->getSchemes() || $route->hasScheme($this->context->getScheme());
  151. if ($requiredMethods) {
  152. if (!\in_array($method, $requiredMethods)) {
  153. if ($hasRequiredScheme) {
  154. $this->allow = array_merge($this->allow, $requiredMethods);
  155. }
  156. continue;
  157. }
  158. }
  159. if (!$hasRequiredScheme) {
  160. $this->allowSchemes = array_merge($this->allowSchemes, $route->getSchemes());
  161. continue;
  162. }
  163. return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, isset($status[1]) ? $status[1] : []));
  164. }
  165. return [];
  166. }
  167. /**
  168. * Returns an array of values to use as request attributes.
  169. *
  170. * As this method requires the Route object, it is not available
  171. * in matchers that do not have access to the matched Route instance
  172. * (like the PHP and Apache matcher dumpers).
  173. *
  174. * @param Route $route The route we are matching against
  175. * @param string $name The name of the route
  176. * @param array $attributes An array of attributes from the matcher
  177. *
  178. * @return array An array of parameters
  179. */
  180. protected function getAttributes(Route $route, $name, array $attributes)
  181. {
  182. $defaults = $route->getDefaults();
  183. if (isset($defaults['_canonical_route'])) {
  184. $name = $defaults['_canonical_route'];
  185. unset($defaults['_canonical_route']);
  186. }
  187. $attributes['_route'] = $name;
  188. return $this->mergeDefaults($attributes, $defaults);
  189. }
  190. /**
  191. * Handles specific route requirements.
  192. *
  193. * @param string $pathinfo The path
  194. * @param string $name The route name
  195. * @param Route $route The route
  196. *
  197. * @return array The first element represents the status, the second contains additional information
  198. */
  199. protected function handleRouteRequirements($pathinfo, $name, Route $route)
  200. {
  201. // expression condition
  202. if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), ['context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)])) {
  203. return [self::REQUIREMENT_MISMATCH, null];
  204. }
  205. return [self::REQUIREMENT_MATCH, null];
  206. }
  207. /**
  208. * Get merged default parameters.
  209. *
  210. * @param array $params The parameters
  211. * @param array $defaults The defaults
  212. *
  213. * @return array Merged default parameters
  214. */
  215. protected function mergeDefaults($params, $defaults)
  216. {
  217. foreach ($params as $key => $value) {
  218. if (!\is_int($key) && null !== $value) {
  219. $defaults[$key] = $value;
  220. }
  221. }
  222. return $defaults;
  223. }
  224. protected function getExpressionLanguage()
  225. {
  226. if (null === $this->expressionLanguage) {
  227. if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  228. throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  229. }
  230. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  231. }
  232. return $this->expressionLanguage;
  233. }
  234. /**
  235. * @internal
  236. */
  237. protected function createRequest($pathinfo)
  238. {
  239. if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
  240. return null;
  241. }
  242. return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), [], [], [
  243. 'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  244. 'SCRIPT_NAME' => $this->context->getBaseUrl(),
  245. ]);
  246. }
  247. }