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