PageRenderTime 26ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/routing/Generator/UrlGenerator.php

https://gitlab.com/Pasantias/pasantiasASLG
PHP | 330 lines | 181 code | 44 blank | 105 comment | 50 complexity | 9e2a8336051828d8d196c4314e524858 MD5 | raw file
  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. foreach ($tokens as $token) {
  138. if ('variable' === $token[0]) {
  139. if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
  140. // check requirement
  141. if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
  142. $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
  143. if ($this->strictRequirements) {
  144. throw new InvalidParameterException($message);
  145. }
  146. if ($this->logger) {
  147. $this->logger->error($message);
  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. } elseif (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) {
  183. // We do this for BC; to be removed if _scheme is not supported anymore
  184. $referenceType = self::ABSOLUTE_URL;
  185. $scheme = $req;
  186. }
  187. if ($hostTokens) {
  188. $routeHost = '';
  189. foreach ($hostTokens as $token) {
  190. if ('variable' === $token[0]) {
  191. if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i', $mergedParams[$token[3]])) {
  192. $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
  193. if ($this->strictRequirements) {
  194. throw new InvalidParameterException($message);
  195. }
  196. if ($this->logger) {
  197. $this->logger->error($message);
  198. }
  199. return;
  200. }
  201. $routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
  202. } else {
  203. $routeHost = $token[1].$routeHost;
  204. }
  205. }
  206. if ($routeHost !== $host) {
  207. $host = $routeHost;
  208. if (self::ABSOLUTE_URL !== $referenceType) {
  209. $referenceType = self::NETWORK_PATH;
  210. }
  211. }
  212. }
  213. if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
  214. $port = '';
  215. if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
  216. $port = ':'.$this->context->getHttpPort();
  217. } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
  218. $port = ':'.$this->context->getHttpsPort();
  219. }
  220. $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
  221. $schemeAuthority .= $host.$port;
  222. }
  223. }
  224. if (self::RELATIVE_PATH === $referenceType) {
  225. $url = self::getRelativePath($this->context->getPathInfo(), $url);
  226. } else {
  227. $url = $schemeAuthority.$this->context->getBaseUrl().$url;
  228. }
  229. // add a query string if needed
  230. $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
  231. return $a == $b ? 0 : 1;
  232. });
  233. if ($extra && $query = http_build_query($extra, '', '&')) {
  234. // "/" and "?" can be left decoded for better user experience, see
  235. // http://tools.ietf.org/html/rfc3986#section-3.4
  236. $url .= '?'.strtr($query, array('%2F' => '/'));
  237. }
  238. return $url;
  239. }
  240. /**
  241. * Returns the target path as relative reference from the base path.
  242. *
  243. * Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
  244. * Both paths must be absolute and not contain relative parts.
  245. * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
  246. * Furthermore, they can be used to reduce the link size in documents.
  247. *
  248. * Example target paths, given a base path of "/a/b/c/d":
  249. * - "/a/b/c/d" -> ""
  250. * - "/a/b/c/" -> "./"
  251. * - "/a/b/" -> "../"
  252. * - "/a/b/c/other" -> "other"
  253. * - "/a/x/y" -> "../../x/y"
  254. *
  255. * @param string $basePath The base path
  256. * @param string $targetPath The target path
  257. *
  258. * @return string The relative target path
  259. */
  260. public static function getRelativePath($basePath, $targetPath)
  261. {
  262. if ($basePath === $targetPath) {
  263. return '';
  264. }
  265. $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
  266. $targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
  267. array_pop($sourceDirs);
  268. $targetFile = array_pop($targetDirs);
  269. foreach ($sourceDirs as $i => $dir) {
  270. if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
  271. unset($sourceDirs[$i], $targetDirs[$i]);
  272. } else {
  273. break;
  274. }
  275. }
  276. $targetDirs[] = $targetFile;
  277. $path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
  278. // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
  279. // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
  280. // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
  281. // (see http://tools.ietf.org/html/rfc3986#section-4.2).
  282. return '' === $path || '/' === $path[0]
  283. || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
  284. ? "./$path" : $path;
  285. }
  286. }