UrlGenerator.php 14 KB

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