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

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