PageRenderTime 51ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/core/Associates/Symfony/Routes/vendor/symfony/routing/Symfony/Component/Routing/Generator/UrlGenerator.php

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