4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Routing\Generator;
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;
22 * UrlGenerator can generate a URL or a path for any route in the RouteCollection
23 * based on the passed parameters.
25 * @author Fabien Potencier <fabien@symfony.com>
26 * @author Tobias Schultze <http://tobion.de>
28 class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface
36 protected $strictRequirements = true;
41 * This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL.
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).
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
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
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
68 public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null)
70 $this->routes = $routes;
71 $this->context = $context;
72 $this->logger = $logger;
78 public function setContext(RequestContext $context)
80 $this->context = $context;
86 public function getContext()
88 return $this->context;
94 public function setStrictRequirements($enabled)
96 $this->strictRequirements = null === $enabled ? null : (bool) $enabled;
102 public function isStrictRequirements()
104 return $this->strictRequirements;
110 public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
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));
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();
119 return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes());
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
127 protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array())
129 $variables = array_flip($variables);
130 $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
132 // all params must be given
133 if ($diff = array_diff_key($variables, $mergedParams)) {
134 throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
139 $message = 'Parameter "{parameter}" for route "{route}" must match "{expected}" ("{given}" given) to generate a corresponding URL.';
140 foreach ($tokens as $token) {
141 if ('variable' === $token[0]) {
142 if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
144 if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#'.(empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) {
145 if ($this->strictRequirements) {
146 throw new InvalidParameterException(strtr($message, array('{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]])));
150 $this->logger->error($message, array('parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]));
156 $url = $token[1].$mergedParams[$token[3]].$url;
161 $url = $token[1].$url;
170 // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
171 $url = strtr(rawurlencode($url), $this->decodedChars);
173 // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
174 // so we need to encode them as they are not used for this purpose here
175 // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
176 $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/'));
177 if ('/..' === substr($url, -3)) {
178 $url = substr($url, 0, -2).'%2E%2E';
179 } elseif ('/.' === substr($url, -2)) {
180 $url = substr($url, 0, -1).'%2E';
183 $schemeAuthority = '';
184 $host = $this->context->getHost();
185 $scheme = $this->context->getScheme();
187 if ($requiredSchemes) {
188 if (!\in_array($scheme, $requiredSchemes, true)) {
189 $referenceType = self::ABSOLUTE_URL;
190 $scheme = current($requiredSchemes);
196 foreach ($hostTokens as $token) {
197 if ('variable' === $token[0]) {
198 if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i'.(empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) {
199 if ($this->strictRequirements) {
200 throw new InvalidParameterException(strtr($message, array('{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]])));
204 $this->logger->error($message, array('parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]));
210 $routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
212 $routeHost = $token[1].$routeHost;
216 if ($routeHost !== $host) {
218 if (self::ABSOLUTE_URL !== $referenceType) {
219 $referenceType = self::NETWORK_PATH;
224 if ((self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) && !empty($host)) {
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();
232 $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
233 $schemeAuthority .= $host.$port;
236 if (self::RELATIVE_PATH === $referenceType) {
237 $url = self::getRelativePath($this->context->getPathInfo(), $url);
239 $url = $schemeAuthority.$this->context->getBaseUrl().$url;
242 // add a query string if needed
243 $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
244 return $a == $b ? 0 : 1;
249 if (isset($defaults['_fragment'])) {
250 $fragment = $defaults['_fragment'];
253 if (isset($extra['_fragment'])) {
254 $fragment = $extra['_fragment'];
255 unset($extra['_fragment']);
258 if ($extra && $query = http_build_query($extra, '', '&', PHP_QUERY_RFC3986)) {
259 // "/" and "?" can be left decoded for better user experience, see
260 // http://tools.ietf.org/html/rfc3986#section-3.4
261 $url .= '?'.strtr($query, array('%2F' => '/'));
264 if ('' !== $fragment) {
265 $url .= '#'.strtr(rawurlencode($fragment), array('%2F' => '/', '%3F' => '?'));
272 * Returns the target path as relative reference from the base path.
274 * Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
275 * Both paths must be absolute and not contain relative parts.
276 * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
277 * Furthermore, they can be used to reduce the link size in documents.
279 * Example target paths, given a base path of "/a/b/c/d":
281 * - "/a/b/c/" -> "./"
283 * - "/a/b/c/other" -> "other"
284 * - "/a/x/y" -> "../../x/y"
286 * @param string $basePath The base path
287 * @param string $targetPath The target path
289 * @return string The relative target path
291 public static function getRelativePath($basePath, $targetPath)
293 if ($basePath === $targetPath) {
297 $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
298 $targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
299 array_pop($sourceDirs);
300 $targetFile = array_pop($targetDirs);
302 foreach ($sourceDirs as $i => $dir) {
303 if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
304 unset($sourceDirs[$i], $targetDirs[$i]);
310 $targetDirs[] = $targetFile;
311 $path = str_repeat('../', \count($sourceDirs)).implode('/', $targetDirs);
313 // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
314 // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
315 // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
316 // (see http://tools.ietf.org/html/rfc3986#section-4.2).
317 return '' === $path || '/' === $path[0]
318 || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)