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

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