You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

279 lines
9.1 KiB

3 years ago
  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 $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()
  65. {
  66. return $this->context;
  67. }
  68. /**
  69. * {@inheritdoc}
  70. */
  71. public function match(string $pathinfo)
  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)
  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. * @return array An array of parameters
  102. *
  103. * @throws NoConfigurationException If no routing configuration could be found
  104. * @throws ResourceNotFoundException If the resource could not be found
  105. * @throws MethodNotAllowedException If the resource was found but the request method is not allowed
  106. */
  107. protected function matchCollection(string $pathinfo, RouteCollection $routes)
  108. {
  109. // HEAD and GET are equivalent as per RFC
  110. if ('HEAD' === $method = $this->context->getMethod()) {
  111. $method = 'GET';
  112. }
  113. $supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface;
  114. $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/';
  115. foreach ($routes as $name => $route) {
  116. $compiledRoute = $route->compile();
  117. $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
  118. $requiredMethods = $route->getMethods();
  119. // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
  120. if ('' !== $staticPrefix && 0 !== strpos($trimmedPathinfo, $staticPrefix)) {
  121. continue;
  122. }
  123. $regex = $compiledRoute->getRegex();
  124. $pos = strrpos($regex, '$');
  125. $hasTrailingSlash = '/' === $regex[$pos - 1];
  126. $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
  127. if (!preg_match($regex, $pathinfo, $matches)) {
  128. continue;
  129. }
  130. $hasTrailingVar = $trimmedPathinfo !== $pathinfo && preg_match('#\{\w+\}/?$#', $route->getPath());
  131. if ($hasTrailingVar && ($hasTrailingSlash || (null === $m = $matches[\count($compiledRoute->getPathVariables())] ?? null) || '/' !== ($m[-1] ?? '/')) && preg_match($regex, $trimmedPathinfo, $m)) {
  132. if ($hasTrailingSlash) {
  133. $matches = $m;
  134. } else {
  135. $hasTrailingVar = false;
  136. }
  137. }
  138. $hostMatches = [];
  139. if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  140. continue;
  141. }
  142. $status = $this->handleRouteRequirements($pathinfo, $name, $route);
  143. if (self::REQUIREMENT_MISMATCH === $status[0]) {
  144. continue;
  145. }
  146. if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
  147. if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) {
  148. return $this->allow = $this->allowSchemes = [];
  149. }
  150. continue;
  151. }
  152. if ($route->getSchemes() && !$route->hasScheme($this->context->getScheme())) {
  153. $this->allowSchemes = array_merge($this->allowSchemes, $route->getSchemes());
  154. continue;
  155. }
  156. if ($requiredMethods && !\in_array($method, $requiredMethods)) {
  157. $this->allow = array_merge($this->allow, $requiredMethods);
  158. continue;
  159. }
  160. return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, $status[1] ?? []));
  161. }
  162. return [];
  163. }
  164. /**
  165. * Returns an array of values to use as request attributes.
  166. *
  167. * As this method requires the Route object, it is not available
  168. * in matchers that do not have access to the matched Route instance
  169. * (like the PHP and Apache matcher dumpers).
  170. *
  171. * @return array An array of parameters
  172. */
  173. protected function getAttributes(Route $route, string $name, array $attributes)
  174. {
  175. $defaults = $route->getDefaults();
  176. if (isset($defaults['_canonical_route'])) {
  177. $name = $defaults['_canonical_route'];
  178. unset($defaults['_canonical_route']);
  179. }
  180. $attributes['_route'] = $name;
  181. return $this->mergeDefaults($attributes, $defaults);
  182. }
  183. /**
  184. * Handles specific route requirements.
  185. *
  186. * @return array The first element represents the status, the second contains additional information
  187. */
  188. protected function handleRouteRequirements(string $pathinfo, string $name, Route $route)
  189. {
  190. // expression condition
  191. if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), ['context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)])) {
  192. return [self::REQUIREMENT_MISMATCH, null];
  193. }
  194. return [self::REQUIREMENT_MATCH, null];
  195. }
  196. /**
  197. * Get merged default parameters.
  198. *
  199. * @return array Merged default parameters
  200. */
  201. protected function mergeDefaults(array $params, array $defaults)
  202. {
  203. foreach ($params as $key => $value) {
  204. if (!\is_int($key) && null !== $value) {
  205. $defaults[$key] = $value;
  206. }
  207. }
  208. return $defaults;
  209. }
  210. protected function getExpressionLanguage()
  211. {
  212. if (null === $this->expressionLanguage) {
  213. if (!class_exists(ExpressionLanguage::class)) {
  214. throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  215. }
  216. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  217. }
  218. return $this->expressionLanguage;
  219. }
  220. /**
  221. * @internal
  222. */
  223. protected function createRequest(string $pathinfo): ?Request
  224. {
  225. if (!class_exists(Request::class)) {
  226. return null;
  227. }
  228. return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), [], [], [
  229. 'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  230. 'SCRIPT_NAME' => $this->context->getBaseUrl(),
  231. ]);
  232. }
  233. }