UrlGenerator.php 15 KB

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