annotate vendor/symfony/routing/Generator/UrlGenerator.php @ 8:50b0d041100e

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