UrlGenerator.php 13 KB

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