UrlGenerator.php 15 KB

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