UrlGenerator.php 13 KB

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