菜谱项目

UrlMatcher.php 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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\Routing\Exception\MethodNotAllowedException;
  12. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  13. use Symfony\Component\Routing\RouteCollection;
  14. use Symfony\Component\Routing\RequestContext;
  15. use Symfony\Component\Routing\Route;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
  18. use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
  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. // check HTTP method requirement
  111. if ($requiredMethods = $route->getMethods()) {
  112. // HEAD and GET are equivalent as per RFC
  113. if ('HEAD' === $method = $this->context->getMethod()) {
  114. $method = 'GET';
  115. }
  116. if (!in_array($method, $requiredMethods)) {
  117. $this->allow = array_merge($this->allow, $requiredMethods);
  118. continue;
  119. }
  120. }
  121. $status = $this->handleRouteRequirements($pathinfo, $name, $route);
  122. if (self::ROUTE_MATCH === $status[0]) {
  123. return $status[1];
  124. }
  125. if (self::REQUIREMENT_MISMATCH === $status[0]) {
  126. continue;
  127. }
  128. return $this->getAttributes($route, $name, array_replace($matches, $hostMatches));
  129. }
  130. }
  131. /**
  132. * Returns an array of values to use as request attributes.
  133. *
  134. * As this method requires the Route object, it is not available
  135. * in matchers that do not have access to the matched Route instance
  136. * (like the PHP and Apache matcher dumpers).
  137. *
  138. * @param Route $route The route we are matching against
  139. * @param string $name The name of the route
  140. * @param array $attributes An array of attributes from the matcher
  141. *
  142. * @return array An array of parameters
  143. */
  144. protected function getAttributes(Route $route, $name, array $attributes)
  145. {
  146. $attributes['_route'] = $name;
  147. return $this->mergeDefaults($attributes, $route->getDefaults());
  148. }
  149. /**
  150. * Handles specific route requirements.
  151. *
  152. * @param string $pathinfo The path
  153. * @param string $name The route name
  154. * @param Route $route The route
  155. *
  156. * @return array The first element represents the status, the second contains additional information
  157. */
  158. protected function handleRouteRequirements($pathinfo, $name, Route $route)
  159. {
  160. // expression condition
  161. if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)))) {
  162. return array(self::REQUIREMENT_MISMATCH, null);
  163. }
  164. // check HTTP scheme requirement
  165. $scheme = $this->context->getScheme();
  166. $status = $route->getSchemes() && !$route->hasScheme($scheme) ? self::REQUIREMENT_MISMATCH : self::REQUIREMENT_MATCH;
  167. return array($status, null);
  168. }
  169. /**
  170. * Get merged default parameters.
  171. *
  172. * @param array $params The parameters
  173. * @param array $defaults The defaults
  174. *
  175. * @return array Merged default parameters
  176. */
  177. protected function mergeDefaults($params, $defaults)
  178. {
  179. foreach ($params as $key => $value) {
  180. if (!is_int($key)) {
  181. $defaults[$key] = $value;
  182. }
  183. }
  184. return $defaults;
  185. }
  186. protected function getExpressionLanguage()
  187. {
  188. if (null === $this->expressionLanguage) {
  189. if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  190. throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  191. }
  192. $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
  193. }
  194. return $this->expressionLanguage;
  195. }
  196. /**
  197. * @internal
  198. */
  199. protected function createRequest($pathinfo)
  200. {
  201. if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
  202. return null;
  203. }
  204. return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), array(), array(), array(
  205. 'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
  206. 'SCRIPT_NAME' => $this->context->getBaseUrl(),
  207. ));
  208. }
  209. }