UrlGenerator.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 Psr\Log\LoggerInterface;
  12. use Symfony\Component\Routing\Exception\InvalidParameterException;
  13. use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
  14. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  15. use Symfony\Component\Routing\RequestContext;
  16. use Symfony\Component\Routing\RouteCollection;
  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. if (\is_bool($referenceType) || \is_string($referenceType)) {
  114. @trigger_error('The hardcoded value you are using for the $referenceType argument of the '.__CLASS__.'::generate method is deprecated since Symfony 2.8 and will not be supported anymore in 3.0. Use the constants defined in the UrlGeneratorInterface instead.', E_USER_DEPRECATED);
  115. if (true === $referenceType) {
  116. $referenceType = self::ABSOLUTE_URL;
  117. } elseif (false === $referenceType) {
  118. $referenceType = self::ABSOLUTE_PATH;
  119. } elseif ('relative' === $referenceType) {
  120. $referenceType = self::RELATIVE_PATH;
  121. } elseif ('network' === $referenceType) {
  122. $referenceType = self::NETWORK_PATH;
  123. }
  124. }
  125. $variables = array_flip($variables);
  126. $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
  127. // all params must be given
  128. if ($diff = array_diff_key($variables, $mergedParams)) {
  129. throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
  130. }
  131. $url = '';
  132. $optional = true;
  133. foreach ($tokens as $token) {
  134. if ('variable' === $token[0]) {
  135. if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
  136. // check requirement
  137. if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
  138. $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
  139. if ($this->strictRequirements) {
  140. throw new InvalidParameterException($message);
  141. }
  142. if ($this->logger) {
  143. $this->logger->error($message);
  144. }
  145. return;
  146. }
  147. $url = $token[1].$mergedParams[$token[3]].$url;
  148. $optional = false;
  149. }
  150. } else {
  151. // static text
  152. $url = $token[1].$url;
  153. $optional = false;
  154. }
  155. }
  156. if ('' === $url) {
  157. $url = '/';
  158. }
  159. // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
  160. $url = strtr(rawurlencode($url), $this->decodedChars);
  161. // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
  162. // so we need to encode them as they are not used for this purpose here
  163. // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
  164. $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/'));
  165. if ('/..' === substr($url, -3)) {
  166. $url = substr($url, 0, -2).'%2E%2E';
  167. } elseif ('/.' === substr($url, -2)) {
  168. $url = substr($url, 0, -1).'%2E';
  169. }
  170. $schemeAuthority = '';
  171. $host = $this->context->getHost();
  172. $scheme = $this->context->getScheme();
  173. if ($requiredSchemes) {
  174. if (!\in_array($scheme, $requiredSchemes, true)) {
  175. $referenceType = self::ABSOLUTE_URL;
  176. $scheme = current($requiredSchemes);
  177. }
  178. } elseif (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) {
  179. // We do this for BC; to be removed if _scheme is not supported anymore
  180. $referenceType = self::ABSOLUTE_URL;
  181. $scheme = $req;
  182. }
  183. if ($hostTokens) {
  184. $routeHost = '';
  185. foreach ($hostTokens as $token) {
  186. if ('variable' === $token[0]) {
  187. if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i', $mergedParams[$token[3]])) {
  188. $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
  189. if ($this->strictRequirements) {
  190. throw new InvalidParameterException($message);
  191. }
  192. if ($this->logger) {
  193. $this->logger->error($message);
  194. }
  195. return;
  196. }
  197. $routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
  198. } else {
  199. $routeHost = $token[1].$routeHost;
  200. }
  201. }
  202. if ($routeHost !== $host) {
  203. $host = $routeHost;
  204. if (self::ABSOLUTE_URL !== $referenceType) {
  205. $referenceType = self::NETWORK_PATH;
  206. }
  207. }
  208. }
  209. if ((self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) && !empty($host)) {
  210. $port = '';
  211. if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
  212. $port = ':'.$this->context->getHttpPort();
  213. } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
  214. $port = ':'.$this->context->getHttpsPort();
  215. }
  216. $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
  217. $schemeAuthority .= $host.$port;
  218. }
  219. if (self::RELATIVE_PATH === $referenceType) {
  220. $url = self::getRelativePath($this->context->getPathInfo(), $url);
  221. } else {
  222. $url = $schemeAuthority.$this->context->getBaseUrl().$url;
  223. }
  224. // add a query string if needed
  225. $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
  226. return $a == $b ? 0 : 1;
  227. });
  228. if ($extra && $query = http_build_query($extra, '', '&')) {
  229. // "/" and "?" can be left decoded for better user experience, see
  230. // http://tools.ietf.org/html/rfc3986#section-3.4
  231. $url .= '?'.strtr($query, array('%2F' => '/'));
  232. }
  233. return $url;
  234. }
  235. /**
  236. * Returns the target path as relative reference from the base path.
  237. *
  238. * Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
  239. * Both paths must be absolute and not contain relative parts.
  240. * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
  241. * Furthermore, they can be used to reduce the link size in documents.
  242. *
  243. * Example target paths, given a base path of "/a/b/c/d":
  244. * - "/a/b/c/d" -> ""
  245. * - "/a/b/c/" -> "./"
  246. * - "/a/b/" -> "../"
  247. * - "/a/b/c/other" -> "other"
  248. * - "/a/x/y" -> "../../x/y"
  249. *
  250. * @param string $basePath The base path
  251. * @param string $targetPath The target path
  252. *
  253. * @return string The relative target path
  254. */
  255. public static function getRelativePath($basePath, $targetPath)
  256. {
  257. if ($basePath === $targetPath) {
  258. return '';
  259. }
  260. $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
  261. $targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
  262. array_pop($sourceDirs);
  263. $targetFile = array_pop($targetDirs);
  264. foreach ($sourceDirs as $i => $dir) {
  265. if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
  266. unset($sourceDirs[$i], $targetDirs[$i]);
  267. } else {
  268. break;
  269. }
  270. }
  271. $targetDirs[] = $targetFile;
  272. $path = str_repeat('../', \count($sourceDirs)).implode('/', $targetDirs);
  273. // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
  274. // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
  275. // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
  276. // (see http://tools.ietf.org/html/rfc3986#section-4.2).
  277. return '' === $path || '/' === $path[0]
  278. || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
  279. ? "./$path" : $path;
  280. }
  281. }