菜谱项目

UrlGenerator.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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\Generator;
  11. use Symfony\Component\Routing\RouteCollection;
  12. use Symfony\Component\Routing\RequestContext;
  13. use Symfony\Component\Routing\Exception\InvalidParameterException;
  14. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  15. use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
  16. use Psr\Log\LoggerInterface;
  17. /**
  18. * UrlGenerator can generate a URL or a path for any route in the RouteCollection
  19. * based on the passed parameters.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. * @author Tobias Schultze <http://tobion.de>
  23. */
  24. class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface
  25. {
  26. protected $routes;
  27. protected $context;
  28. /**
  29. * @var bool|null
  30. */
  31. protected $strictRequirements = true;
  32. protected $logger;
  33. /**
  34. * This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL.
  35. *
  36. * PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars
  37. * to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g.
  38. * "?" and "#" (would be interpreted wrongly as query and fragment identifier),
  39. * "'" and """ (are used as delimiters in HTML).
  40. */
  41. protected $decodedChars = array(
  42. // the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
  43. // some webservers don't allow the slash in encoded form in the path for security reasons anyway
  44. // see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
  45. '%2F' => '/',
  46. // the following chars are general delimiters in the URI specification but have only special meaning in the authority component
  47. // so they can safely be used in the path in unencoded form
  48. '%40' => '@',
  49. '%3A' => ':',
  50. // these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally
  51. // so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability
  52. '%3B' => ';',
  53. '%2C' => ',',
  54. '%3D' => '=',
  55. '%2B' => '+',
  56. '%21' => '!',
  57. '%2A' => '*',
  58. '%7C' => '|',
  59. );
  60. public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null)
  61. {
  62. $this->routes = $routes;
  63. $this->context = $context;
  64. $this->logger = $logger;
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public function setContext(RequestContext $context)
  70. {
  71. $this->context = $context;
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function getContext()
  77. {
  78. return $this->context;
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. public function setStrictRequirements($enabled)
  84. {
  85. $this->strictRequirements = null === $enabled ? null : (bool) $enabled;
  86. }
  87. /**
  88. * {@inheritdoc}
  89. */
  90. public function isStrictRequirements()
  91. {
  92. return $this->strictRequirements;
  93. }
  94. /**
  95. * {@inheritdoc}
  96. */
  97. public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
  98. {
  99. if (null === $route = $this->routes->get($name)) {
  100. throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
  101. }
  102. // the Route has a cache of its own and is not recompiled as long as it does not get modified
  103. $compiledRoute = $route->compile();
  104. return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes());
  105. }
  106. /**
  107. * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
  108. * @throws InvalidParameterException When a parameter value for a placeholder is not correct because
  109. * it does not match the requirement
  110. */
  111. protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array())
  112. {
  113. $variables = array_flip($variables);
  114. $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
  115. // all params must be given
  116. if ($diff = array_diff_key($variables, $mergedParams)) {
  117. throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
  118. }
  119. $url = '';
  120. $optional = true;
  121. $message = 'Parameter "{parameter}" for route "{route}" must match "{expected}" ("{given}" given) to generate a corresponding URL.';
  122. foreach ($tokens as $token) {
  123. if ('variable' === $token[0]) {
  124. if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
  125. // check requirement
  126. if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#'.(empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) {
  127. if ($this->strictRequirements) {
  128. throw new InvalidParameterException(strtr($message, array('{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]])));
  129. }
  130. if ($this->logger) {
  131. $this->logger->error($message, array('parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]));
  132. }
  133. return;
  134. }
  135. $url = $token[1].$mergedParams[$token[3]].$url;
  136. $optional = false;
  137. }
  138. } else {
  139. // static text
  140. $url = $token[1].$url;
  141. $optional = false;
  142. }
  143. }
  144. if ('' === $url) {
  145. $url = '/';
  146. }
  147. // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
  148. $url = strtr(rawurlencode($url), $this->decodedChars);
  149. // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
  150. // so we need to encode them as they are not used for this purpose here
  151. // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
  152. $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/'));
  153. if ('/..' === substr($url, -3)) {
  154. $url = substr($url, 0, -2).'%2E%2E';
  155. } elseif ('/.' === substr($url, -2)) {
  156. $url = substr($url, 0, -1).'%2E';
  157. }
  158. $schemeAuthority = '';
  159. if ($host = $this->context->getHost()) {
  160. $scheme = $this->context->getScheme();
  161. if ($requiredSchemes) {
  162. if (!in_array($scheme, $requiredSchemes, true)) {
  163. $referenceType = self::ABSOLUTE_URL;
  164. $scheme = current($requiredSchemes);
  165. }
  166. }
  167. if ($hostTokens) {
  168. $routeHost = '';
  169. foreach ($hostTokens as $token) {
  170. if ('variable' === $token[0]) {
  171. if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i'.(empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) {
  172. if ($this->strictRequirements) {
  173. throw new InvalidParameterException(strtr($message, array('{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]])));
  174. }
  175. if ($this->logger) {
  176. $this->logger->error($message, array('parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]));
  177. }
  178. return;
  179. }
  180. $routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
  181. } else {
  182. $routeHost = $token[1].$routeHost;
  183. }
  184. }
  185. if ($routeHost !== $host) {
  186. $host = $routeHost;
  187. if (self::ABSOLUTE_URL !== $referenceType) {
  188. $referenceType = self::NETWORK_PATH;
  189. }
  190. }
  191. }
  192. if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
  193. $port = '';
  194. if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
  195. $port = ':'.$this->context->getHttpPort();
  196. } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
  197. $port = ':'.$this->context->getHttpsPort();
  198. }
  199. $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
  200. $schemeAuthority .= $host.$port;
  201. }
  202. }
  203. if (self::RELATIVE_PATH === $referenceType) {
  204. $url = self::getRelativePath($this->context->getPathInfo(), $url);
  205. } else {
  206. $url = $schemeAuthority.$this->context->getBaseUrl().$url;
  207. }
  208. // add a query string if needed
  209. $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
  210. return $a == $b ? 0 : 1;
  211. });
  212. // extract fragment
  213. $fragment = '';
  214. if (isset($defaults['_fragment'])) {
  215. $fragment = $defaults['_fragment'];
  216. }
  217. if (isset($extra['_fragment'])) {
  218. $fragment = $extra['_fragment'];
  219. unset($extra['_fragment']);
  220. }
  221. if ($extra && $query = http_build_query($extra, '', '&', PHP_QUERY_RFC3986)) {
  222. // "/" and "?" can be left decoded for better user experience, see
  223. // http://tools.ietf.org/html/rfc3986#section-3.4
  224. $url .= '?'.strtr($query, array('%2F' => '/'));
  225. }
  226. if ('' !== $fragment) {
  227. $url .= '#'.strtr(rawurlencode($fragment), array('%2F' => '/', '%3F' => '?'));
  228. }
  229. return $url;
  230. }
  231. /**
  232. * Returns the target path as relative reference from the base path.
  233. *
  234. * Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
  235. * Both paths must be absolute and not contain relative parts.
  236. * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
  237. * Furthermore, they can be used to reduce the link size in documents.
  238. *
  239. * Example target paths, given a base path of "/a/b/c/d":
  240. * - "/a/b/c/d" -> ""
  241. * - "/a/b/c/" -> "./"
  242. * - "/a/b/" -> "../"
  243. * - "/a/b/c/other" -> "other"
  244. * - "/a/x/y" -> "../../x/y"
  245. *
  246. * @param string $basePath The base path
  247. * @param string $targetPath The target path
  248. *
  249. * @return string The relative target path
  250. */
  251. public static function getRelativePath($basePath, $targetPath)
  252. {
  253. if ($basePath === $targetPath) {
  254. return '';
  255. }
  256. $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
  257. $targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
  258. array_pop($sourceDirs);
  259. $targetFile = array_pop($targetDirs);
  260. foreach ($sourceDirs as $i => $dir) {
  261. if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
  262. unset($sourceDirs[$i], $targetDirs[$i]);
  263. } else {
  264. break;
  265. }
  266. }
  267. $targetDirs[] = $targetFile;
  268. $path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
  269. // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
  270. // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
  271. // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
  272. // (see http://tools.ietf.org/html/rfc3986#section-4.2).
  273. return '' === $path || '/' === $path[0]
  274. || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
  275. ? "./$path" : $path;
  276. }
  277. }