annotate vendor/symfony/routing/Generator/UrlGenerator.php @ 19:fa3358dc1485 tip

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