UrlMatcher.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. public const REQUIREMENT_MATCH = 0;
  28. public const REQUIREMENT_MISMATCH = 1;
  29. public const ROUTE_MATCH = 2;
  30. /**
  31. * Collects HTTP methods that would be allowed for the request.
  32. */
  33. protected array $allow = [];
  34. /**
  35. * Collects URI schemes that would be allowed for the request.
  36. *
  37. * @internal
  38. */
  39. protected array $allowSchemes = [];
  40. protected ?Request $request = null;
  41. protected ExpressionLanguage $expressionLanguage;
  42. /**
  43. * @var ExpressionFunctionProviderInterface[]
  44. */
  45. protected array $expressionLanguageProviders = [];
  46. public function __construct(
  47. protected RouteCollection $routes,
  48. protected RequestContext $context,
  49. ) {
  50. }
  51. public function setContext(RequestContext $context): void
  52. {
  53. $this->context = $context;
  54. }
  55. public function getContext(): RequestContext
  56. {
  57. return $this->context;
  58. }
  59. public function match(string $pathinfo): array
  60. {
  61. $this->allow = $this->allowSchemes = [];
  62. $pathinfo = '' === ($pathinfo = rawurldecode($pathinfo)) ? '/' : $pathinfo;
  63. if ($ret = $this->matchCollection($pathinfo, $this->routes)) {
  64. return $ret;
  65. }
  66. if ('/' === $pathinfo && !$this->allow && !$this->allowSchemes) {
  67. throw new NoConfigurationException();
  68. }
  69. throw 0 < \count($this->allow) ? new MethodNotAllowedException(array_unique($this->allow)) : new ResourceNotFoundException(\sprintf('No routes found for "%s".', $pathinfo));
  70. }
  71. public function matchRequest(Request $request): array
  72. {
  73. $this->request = $request;
  74. $originalContext = $this->context;
  75. $this->context = (clone $originalContext)->fromRequest($request);
  76. try {
  77. return $this->match($request->getPathInfo());
  78. } finally {
  79. $this->context = $originalContext;
  80. $this->request = null;
  81. }
  82. }
  83. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider): void
  84. {
  85. $this->expressionLanguageProviders[] = $provider;
  86. }
  87. /**
  88. * Tries to match a URL with a set of routes.
  89. *
  90. * @param string $pathinfo The path info to be parsed
  91. *
  92. * @throws NoConfigurationException If no routing configuration could be found
  93. * @throws ResourceNotFoundException If the resource could not be found
  94. * @throws MethodNotAllowedException If the resource was found but the request method is not allowed
  95. */
  96. protected function matchCollection(string $pathinfo, RouteCollection $routes): array
  97. {
  98. // HEAD and GET are equivalent as per RFC
  99. if ('HEAD' === $method = $this->context->getMethod()) {
  100. $method = 'GET';
  101. }
  102. $supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface;
  103. $trimmedPathinfo = '' === ($trimmedPathinfo = rtrim($pathinfo, '/')) ? '/' : $trimmedPathinfo;
  104. foreach ($routes as $name => $route) {
  105. $compiledRoute = $route->compile();
  106. $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
  107. $requiredMethods = $route->getMethods();
  108. // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
  109. if ('' !== $staticPrefix && !str_starts_with($trimmedPathinfo, $staticPrefix)) {
  110. continue;
  111. }
  112. $regex = $compiledRoute->getRegex();
  113. $pos = strrpos($regex, '$');
  114. $hasTrailingSlash = '/' === $regex[$pos - 1];
  115. $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
  116. if (!preg_match($regex, $pathinfo, $matches)) {
  117. continue;
  118. }
  119. $hasTrailingVar = $trimmedPathinfo !== $pathinfo && preg_match('#\{[\w\x80-\xFF]+\}/?$#', $route->getPath());
  120. if ($hasTrailingVar && ($hasTrailingSlash || (null === $m = $matches[\count($compiledRoute->getPathVariables())] ?? null) || '/' !== ($m[-1] ?? '/')) && preg_match($regex, $trimmedPathinfo, $m)) {
  121. if ($hasTrailingSlash) {
  122. $matches = $m;
  123. } else {
  124. $hasTrailingVar = false;
  125. }
  126. }
  127. $hostMatches = [];
  128. if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  129. continue;
  130. }
  131. $attributes = $this->getAttributes($route, $name, array_replace($matches, $hostMatches));
  132. $status = $this->handleRouteRequirements($pathinfo, $name, $route, $attributes);
  133. if (self::REQUIREMENT_MISMATCH === $status[0]) {
  134. continue;
  135. }
  136. if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
  137. if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods, true))) {
  138. return $this->allow = $this->allowSchemes = [];
  139. }
  140. continue;
  141. }
  142. if ($route->getSchemes() && !$route->hasScheme($this->context->getScheme())) {
  143. $this->allowSchemes = array_merge($this->allowSchemes, $route->getSchemes());
  144. continue;
  145. }
  146. if ($requiredMethods && !\in_array($method, $requiredMethods, true)) {
  147. $this->allow = array_merge($this->allow, $requiredMethods);
  148. continue;
  149. }
  150. return array_replace($attributes, $status[1] ?? []);
  151. }
  152. return [];
  153. }
  154. /**
  155. * Returns an array of values to use as request attributes.
  156. *
  157. * As this method requires the Route object, it is not available
  158. * in matchers that do not have access to the matched Route instance
  159. * (like the PHP and Apache matcher dumpers).
  160. */
  161. protected function getAttributes(Route $route, string $name, array $attributes): array
  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. if ($mapping = $route->getOption('mapping')) {
  170. $attributes['_route_mapping'] = $mapping;
  171. }
  172. return $this->mergeDefaults($attributes, $defaults);
  173. }
  174. /**
  175. * Handles specific route requirements.
  176. *
  177. * @return array The first element represents the status, the second contains additional information
  178. */
  179. protected function handleRouteRequirements(string $pathinfo, string $name, Route $route, array $routeParameters): array
  180. {
  181. // expression condition
  182. if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), [
  183. 'context' => $this->context,
  184. 'request' => $this->request ?: $this->createRequest($pathinfo),
  185. 'params' => $routeParameters,
  186. ])) {
  187. return [self::REQUIREMENT_MISMATCH, null];
  188. }
  189. return [self::REQUIREMENT_MATCH, null];
  190. }
  191. /**
  192. * Get merged default parameters.
  193. */
  194. protected function mergeDefaults(array $params, array $defaults): array
  195. {
  196. foreach ($params as $key => $value) {
  197. if (!\is_int($key) && null !== $value) {
  198. $defaults[$key] = $value;
  199. }
  200. }
  201. return $defaults;
  202. }
  203. protected function getExpressionLanguage(): ExpressionLanguage
  204. {
  205. if (!isset($this->expressionLanguage)) {
  206. if (!class_exists(ExpressionLanguage::class)) {
  207. throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed. Try running "composer require symfony/expression-language".');
  208. }
  209. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  210. }
  211. return $this->expressionLanguage;
  212. }
  213. /**
  214. * @internal
  215. */
  216. protected function createRequest(string $pathinfo): ?Request
  217. {
  218. if (!class_exists(Request::class)) {
  219. return null;
  220. }
  221. return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), [], [], [
  222. 'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  223. 'SCRIPT_NAME' => $this->context->getBaseUrl(),
  224. ]);
  225. }
  226. }