UrlMatcher.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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\ResourceNotFoundException;
  16. use Symfony\Component\Routing\RequestContext;
  17. use Symfony\Component\Routing\Route;
  18. use Symfony\Component\Routing\RouteCollection;
  19. /**
  20. * UrlMatcher matches URL based on a set of routes.
  21. *
  22. * @author Fabien Potencier <fabien@symfony.com>
  23. */
  24. class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
  25. {
  26. const REQUIREMENT_MATCH = 0;
  27. const REQUIREMENT_MISMATCH = 1;
  28. const ROUTE_MATCH = 2;
  29. protected $context;
  30. protected $allow = array();
  31. protected $routes;
  32. protected $request;
  33. protected $expressionLanguage;
  34. /**
  35. * @var ExpressionFunctionProviderInterface[]
  36. */
  37. protected $expressionLanguageProviders = array();
  38. public function __construct(RouteCollection $routes, RequestContext $context)
  39. {
  40. $this->routes = $routes;
  41. $this->context = $context;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function setContext(RequestContext $context)
  47. {
  48. $this->context = $context;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function getContext()
  54. {
  55. return $this->context;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function match($pathinfo)
  61. {
  62. $this->allow = array();
  63. if ($ret = $this->matchCollection(rawurldecode($pathinfo), $this->routes)) {
  64. return $ret;
  65. }
  66. throw 0 < \count($this->allow)
  67. ? new MethodNotAllowedException(array_unique($this->allow))
  68. : new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function matchRequest(Request $request)
  74. {
  75. $this->request = $request;
  76. $ret = $this->match($request->getPathInfo());
  77. $this->request = null;
  78. return $ret;
  79. }
  80. public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
  81. {
  82. $this->expressionLanguageProviders[] = $provider;
  83. }
  84. /**
  85. * Tries to match a URL with a set of routes.
  86. *
  87. * @param string $pathinfo The path info to be parsed
  88. * @param RouteCollection $routes The set of routes
  89. *
  90. * @return array An array of parameters
  91. *
  92. * @throws ResourceNotFoundException If the resource could not be found
  93. * @throws MethodNotAllowedException If the resource was found but the request method is not allowed
  94. */
  95. protected function matchCollection($pathinfo, RouteCollection $routes)
  96. {
  97. foreach ($routes as $name => $route) {
  98. $compiledRoute = $route->compile();
  99. // check the static prefix of the URL first. Only use the more expensive preg_match when it matches
  100. if ('' !== $compiledRoute->getStaticPrefix() && 0 !== strpos($pathinfo, $compiledRoute->getStaticPrefix())) {
  101. continue;
  102. }
  103. if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
  104. continue;
  105. }
  106. $hostMatches = array();
  107. if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
  108. continue;
  109. }
  110. $status = $this->handleRouteRequirements($pathinfo, $name, $route);
  111. if (self::REQUIREMENT_MISMATCH === $status[0]) {
  112. continue;
  113. }
  114. // check HTTP method requirement
  115. if ($requiredMethods = $route->getMethods()) {
  116. // HEAD and GET are equivalent as per RFC
  117. if ('HEAD' === $method = $this->context->getMethod()) {
  118. $method = 'GET';
  119. }
  120. if (!\in_array($method, $requiredMethods)) {
  121. if (self::REQUIREMENT_MATCH === $status[0]) {
  122. $this->allow = array_merge($this->allow, $requiredMethods);
  123. }
  124. continue;
  125. }
  126. }
  127. if (self::ROUTE_MATCH === $status[0]) {
  128. return $status[1];
  129. }
  130. return $this->getAttributes($route, $name, array_replace($matches, $hostMatches));
  131. }
  132. }
  133. /**
  134. * Returns an array of values to use as request attributes.
  135. *
  136. * As this method requires the Route object, it is not available
  137. * in matchers that do not have access to the matched Route instance
  138. * (like the PHP and Apache matcher dumpers).
  139. *
  140. * @param Route $route The route we are matching against
  141. * @param string $name The name of the route
  142. * @param array $attributes An array of attributes from the matcher
  143. *
  144. * @return array An array of parameters
  145. */
  146. protected function getAttributes(Route $route, $name, array $attributes)
  147. {
  148. $attributes['_route'] = $name;
  149. return $this->mergeDefaults($attributes, $route->getDefaults());
  150. }
  151. /**
  152. * Handles specific route requirements.
  153. *
  154. * @param string $pathinfo The path
  155. * @param string $name The route name
  156. * @param Route $route The route
  157. *
  158. * @return array The first element represents the status, the second contains additional information
  159. */
  160. protected function handleRouteRequirements($pathinfo, $name, Route $route)
  161. {
  162. // expression condition
  163. if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)))) {
  164. return array(self::REQUIREMENT_MISMATCH, null);
  165. }
  166. // check HTTP scheme requirement
  167. $scheme = $this->context->getScheme();
  168. $status = $route->getSchemes() && !$route->hasScheme($scheme) ? self::REQUIREMENT_MISMATCH : self::REQUIREMENT_MATCH;
  169. return array($status, null);
  170. }
  171. /**
  172. * Get merged default parameters.
  173. *
  174. * @param array $params The parameters
  175. * @param array $defaults The defaults
  176. *
  177. * @return array Merged default parameters
  178. */
  179. protected function mergeDefaults($params, $defaults)
  180. {
  181. foreach ($params as $key => $value) {
  182. if (!\is_int($key)) {
  183. $defaults[$key] = $value;
  184. }
  185. }
  186. return $defaults;
  187. }
  188. protected function getExpressionLanguage()
  189. {
  190. if (null === $this->expressionLanguage) {
  191. if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  192. throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  193. }
  194. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  195. }
  196. return $this->expressionLanguage;
  197. }
  198. /**
  199. * @internal
  200. */
  201. protected function createRequest($pathinfo)
  202. {
  203. if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
  204. return null;
  205. }
  206. return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), array(), array(), array(
  207. 'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  208. 'SCRIPT_NAME' => $this->context->getBaseUrl(),
  209. ));
  210. }
  211. }