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 Symfony\Component\Routing\RouteCollection;
15 use Symfony\Component\Routing\RequestContext;
16 use Symfony\Component\Routing\Exception\InvalidParameterException;
17 use Symfony\Component\Routing\Exception\RouteNotFoundException;
18 use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
19 use Psr\Log\LoggerInterface;
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
31 * @var RouteCollection
43 protected $strictRequirements = true;
46 * @var LoggerInterface|null
51 * This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL.
53 * PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars
54 * to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g.
55 * "?" and "#" (would be interpreted wrongly as query and fragment identifier),
56 * "'" and """ (are used as delimiters in HTML).
58 protected $decodedChars = array(
59 // the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
60 // some webservers don't allow the slash in encoded form in the path for security reasons anyway
61 // see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
63 // the following chars are general delimiters in the URI specification but have only special meaning in the authority component
64 // so they can safely be used in the path in unencoded form
67 // these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally
68 // so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability
81 * @param RouteCollection $routes A RouteCollection instance
82 * @param RequestContext $context The context
83 * @param LoggerInterface|null $logger A logger instance
85 public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null)
87 $this->routes = $routes;
88 $this->context = $context;
89 $this->logger = $logger;
95 public function setContext(RequestContext $context)
97 $this->context = $context;
103 public function getContext()
105 return $this->context;
111 public function setStrictRequirements($enabled)
113 $this->strictRequirements = null === $enabled ? null : (bool) $enabled;
119 public function isStrictRequirements()
121 return $this->strictRequirements;
127 public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
129 if (null === $route = $this->routes->get($name)) {
130 throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
133 // the Route has a cache of its own and is not recompiled as long as it does not get modified
134 $compiledRoute = $route->compile();
136 return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes());
140 * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
141 * @throws InvalidParameterException When a parameter value for a placeholder is not correct because
142 * it does not match the requirement
144 protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array())
146 $variables = array_flip($variables);
147 $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
149 // all params must be given
150 if ($diff = array_diff_key($variables, $mergedParams)) {
151 throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
156 $message = 'Parameter "{parameter}" for route "{route}" must match "{expected}" ("{given}" given) to generate a corresponding URL.';
157 foreach ($tokens as $token) {
158 if ('variable' === $token[0]) {
159 if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
161 if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#'.(empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) {
162 if ($this->strictRequirements) {
163 throw new InvalidParameterException(strtr($message, array('{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]])));
167 $this->logger->error($message, array('parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]));
173 $url = $token[1].$mergedParams[$token[3]].$url;
178 $url = $token[1].$url;
187 // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
188 $url = strtr(rawurlencode($url), $this->decodedChars);
190 // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
191 // so we need to encode them as they are not used for this purpose here
192 // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
193 $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/'));
194 if ('/..' === substr($url, -3)) {
195 $url = substr($url, 0, -2).'%2E%2E';
196 } elseif ('/.' === substr($url, -2)) {
197 $url = substr($url, 0, -1).'%2E';
200 $schemeAuthority = '';
201 if ($host = $this->context->getHost()) {
202 $scheme = $this->context->getScheme();
204 if ($requiredSchemes) {
205 if (!in_array($scheme, $requiredSchemes, true)) {
206 $referenceType = self::ABSOLUTE_URL;
207 $scheme = current($requiredSchemes);
213 foreach ($hostTokens as $token) {
214 if ('variable' === $token[0]) {
215 if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i'.(empty($token[4]) ? '' : 'u'), $mergedParams[$token[3]])) {
216 if ($this->strictRequirements) {
217 throw new InvalidParameterException(strtr($message, array('{parameter}' => $token[3], '{route}' => $name, '{expected}' => $token[2], '{given}' => $mergedParams[$token[3]])));
221 $this->logger->error($message, array('parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]));
227 $routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
229 $routeHost = $token[1].$routeHost;
233 if ($routeHost !== $host) {
235 if (self::ABSOLUTE_URL !== $referenceType) {
236 $referenceType = self::NETWORK_PATH;
241 if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
243 if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
244 $port = ':'.$this->context->getHttpPort();
245 } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
246 $port = ':'.$this->context->getHttpsPort();
249 $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
250 $schemeAuthority .= $host.$port;
254 if (self::RELATIVE_PATH === $referenceType) {
255 $url = self::getRelativePath($this->context->getPathInfo(), $url);
257 $url = $schemeAuthority.$this->context->getBaseUrl().$url;
260 // add a query string if needed
261 $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
262 return $a == $b ? 0 : 1;
267 if (isset($defaults['_fragment'])) {
268 $fragment = $defaults['_fragment'];
271 if (isset($extra['_fragment'])) {
272 $fragment = $extra['_fragment'];
273 unset($extra['_fragment']);
276 if ($extra && $query = http_build_query($extra, '', '&', PHP_QUERY_RFC3986)) {
277 // "/" and "?" can be left decoded for better user experience, see
278 // http://tools.ietf.org/html/rfc3986#section-3.4
279 $url .= '?'.strtr($query, array('%2F' => '/'));
282 if ('' !== $fragment) {
283 $url .= '#'.strtr(rawurlencode($fragment), array('%2F' => '/', '%3F' => '?'));
290 * Returns the target path as relative reference from the base path.
292 * Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
293 * Both paths must be absolute and not contain relative parts.
294 * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
295 * Furthermore, they can be used to reduce the link size in documents.
297 * Example target paths, given a base path of "/a/b/c/d":
299 * - "/a/b/c/" -> "./"
301 * - "/a/b/c/other" -> "other"
302 * - "/a/x/y" -> "../../x/y"
304 * @param string $basePath The base path
305 * @param string $targetPath The target path
307 * @return string The relative target path
309 public static function getRelativePath($basePath, $targetPath)
311 if ($basePath === $targetPath) {
315 $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
316 $targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
317 array_pop($sourceDirs);
318 $targetFile = array_pop($targetDirs);
320 foreach ($sourceDirs as $i => $dir) {
321 if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
322 unset($sourceDirs[$i], $targetDirs[$i]);
328 $targetDirs[] = $targetFile;
329 $path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
331 // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
332 // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
333 // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
334 // (see http://tools.ietf.org/html/rfc3986#section-4.2).
335 return '' === $path || '/' === $path[0]
336 || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)