UrlMatcher.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. protected $allow = [];
  32. protected $routes;
  33. protected $request;
  34. protected $expressionLanguage;
  35. /**
  36. * @var ExpressionFunctionProviderInterface[]
  37. */
  38. protected $expressionLanguageProviders = [];
  39. public function __construct(RouteCollection $routes, RequestContext $context)
  40. {
  41. $this->routes = $routes;
  42. $this->context = $context;
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function setContext(RequestContext $context)
  48. {
  49. $this->context = $context;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function getContext()
  55. {
  56. return $this->context;
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function match($pathinfo)
  62. {
  63. $this->allow = [];
  64. if ($ret = $this->matchCollection(rawurldecode($pathinfo), $this->routes)) {
  65. return $ret;
  66. }
  67. if ('/' === $pathinfo && !$this->allow) {
  68. throw new NoConfigurationException();
  69. }
  70. throw 0 < \count($this->allow)
  71. ? new MethodNotAllowedException(array_unique($this->allow))
  72. : new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function matchRequest(Request $request)
  78. {
  79. $this->request = $request;
  80. $ret = $this->match($request->getPathInfo());
  81. $this->request = null;
  82. return $ret;
  83. }
  84. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  85. {
  86. $this->expressionLanguageProviders[] = $provider;
  87. }
  88. /**
  89. * Tries to match a URL with a set of routes.
  90. *
  91. * @param string $pathinfo The path info to be parsed
  92. * @param RouteCollection $routes The set of routes
  93. *
  94. * @return array An array of parameters
  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($pathinfo, RouteCollection $routes)
  101. {
  102. // HEAD and GET are equivalent as per RFC
  103. if ('HEAD' === $method = $this->context->getMethod()) {
  104. $method = 'GET';
  105. }
  106. $supportsTrailingSlash = '/' !== $pathinfo && '' !== $pathinfo && $this instanceof RedirectableUrlMatcherInterface;
  107. foreach ($routes as $name => $route) {
  108. $compiledRoute = $route->compile();
  109. $staticPrefix = $compiledRoute->getStaticPrefix();
  110. $requiredMethods = $route->getMethods();
  111. // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
  112. if ('' === $staticPrefix || 0 === strpos($pathinfo, $staticPrefix)) {
  113. // no-op
  114. } elseif (!$supportsTrailingSlash || ($requiredMethods && !\in_array('GET', $requiredMethods)) || 'GET' !== $method) {
  115. continue;
  116. } elseif ('/' === substr($staticPrefix, -1) && substr($staticPrefix, 0, -1) === $pathinfo) {
  117. return $this->allow = [];
  118. } else {
  119. continue;
  120. }
  121. $regex = $compiledRoute->getRegex();
  122. if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
  123. $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
  124. $hasTrailingSlash = true;
  125. } else {
  126. $hasTrailingSlash = false;
  127. }
  128. if (!preg_match($regex, $pathinfo, $matches)) {
  129. continue;
  130. }
  131. if ($hasTrailingSlash && '/' !== substr($pathinfo, -1)) {
  132. if ((!$requiredMethods || \in_array('GET', $requiredMethods)) && 'GET' === $method) {
  133. return $this->allow = [];
  134. }
  135. continue;
  136. }
  137. $hostMatches = [];
  138. if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  139. continue;
  140. }
  141. $status = $this->handleRouteRequirements($pathinfo, $name, $route);
  142. if (self::REQUIREMENT_MISMATCH === $status[0]) {
  143. continue;
  144. }
  145. // check HTTP method requirement
  146. if ($requiredMethods) {
  147. if (!\in_array($method, $requiredMethods)) {
  148. if (self::REQUIREMENT_MATCH === $status[0]) {
  149. $this->allow = array_merge($this->allow, $requiredMethods);
  150. }
  151. continue;
  152. }
  153. }
  154. return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, isset($status[1]) ? $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. * @param Route $route The route we are matching against
  166. * @param string $name The name of the route
  167. * @param array $attributes An array of attributes from the matcher
  168. *
  169. * @return array An array of parameters
  170. */
  171. protected function getAttributes(Route $route, $name, array $attributes)
  172. {
  173. $attributes['_route'] = $name;
  174. return $this->mergeDefaults($attributes, $route->getDefaults());
  175. }
  176. /**
  177. * Handles specific route requirements.
  178. *
  179. * @param string $pathinfo The path
  180. * @param string $name The route name
  181. * @param Route $route The route
  182. *
  183. * @return array The first element represents the status, the second contains additional information
  184. */
  185. protected function handleRouteRequirements($pathinfo, $name, Route $route)
  186. {
  187. // expression condition
  188. if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), ['context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)])) {
  189. return [self::REQUIREMENT_MISMATCH, null];
  190. }
  191. // check HTTP scheme requirement
  192. $scheme = $this->context->getScheme();
  193. $status = $route->getSchemes() && !$route->hasScheme($scheme) ? self::REQUIREMENT_MISMATCH : self::REQUIREMENT_MATCH;
  194. return [$status, null];
  195. }
  196. /**
  197. * Get merged default parameters.
  198. *
  199. * @param array $params The parameters
  200. * @param array $defaults The defaults
  201. *
  202. * @return array Merged default parameters
  203. */
  204. protected function mergeDefaults($params, $defaults)
  205. {
  206. foreach ($params as $key => $value) {
  207. if (!\is_int($key)) {
  208. $defaults[$key] = $value;
  209. }
  210. }
  211. return $defaults;
  212. }
  213. protected function getExpressionLanguage()
  214. {
  215. if (null === $this->expressionLanguage) {
  216. if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  217. throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  218. }
  219. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  220. }
  221. return $this->expressionLanguage;
  222. }
  223. /**
  224. * @internal
  225. */
  226. protected function createRequest($pathinfo)
  227. {
  228. if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
  229. return null;
  230. }
  231. return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), [], [], [
  232. 'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  233. 'SCRIPT_NAME' => $this->context->getBaseUrl(),
  234. ]);
  235. }
  236. }