3 namespace Drupal\Core\Routing;
5 use Drupal\Core\GeneratedUrl;
6 use Drupal\Core\Render\BubbleableMetadata;
7 use Symfony\Component\HttpFoundation\RequestStack;
8 use Symfony\Component\Routing\RequestContext as SymfonyRequestContext;
9 use Symfony\Component\Routing\Route as SymfonyRoute;
10 use Symfony\Component\Routing\Exception\RouteNotFoundException;
11 use Drupal\Component\Utility\UrlHelper;
12 use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
13 use Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface;
14 use Symfony\Component\Routing\Exception\InvalidParameterException;
15 use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
18 * Generates URLs from route names and parameters.
20 class UrlGenerator implements UrlGeneratorInterface {
25 * @var \Drupal\Core\Routing\RouteProviderInterface
35 * A request stack object.
37 * @var \Symfony\Component\HttpFoundation\RequestStack
39 protected $requestStack;
42 * The path processor to convert the system path to one suitable for urls.
44 * @var \Drupal\Core\PathProcessor\OutboundPathProcessorInterface
46 protected $pathProcessor;
49 * The route processor.
51 * @var \Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface
53 protected $routeProcessor;
56 * Overrides characters that will not be percent-encoded in the path segment.
58 * The first two elements are the first two parameters of str_replace(), so
59 * if you override this variable you can also use arrays for the encoded
60 * and decoded characters.
62 * @see \Symfony\Component\Routing\Generator\UrlGenerator
64 protected $decodedChars = [
65 // the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
66 // some webservers don't allow the slash in encoded form in the path for security reasons anyway
67 // see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
68 '%2F', // Map from these encoded characters.
69 '/', // Map to these decoded characters.
73 * Constructs a new generator object.
75 * @param \Drupal\Core\Routing\RouteProviderInterface $provider
76 * The route provider to be searched for routes.
77 * @param \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $path_processor
78 * The path processor to convert the system path to one suitable for urls.
79 * @param \Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface $route_processor
80 * The route processor.
81 * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
82 * A request stack object.
83 * @param string[] $filter_protocols
84 * (optional) An array of protocols allowed for URL generation.
86 public function __construct(RouteProviderInterface $provider, OutboundPathProcessorInterface $path_processor, OutboundRouteProcessorInterface $route_processor, RequestStack $request_stack, array $filter_protocols = ['http', 'https']) {
87 $this->provider = $provider;
88 $this->context = new RequestContext();
90 $this->pathProcessor = $path_processor;
91 $this->routeProcessor = $route_processor;
92 UrlHelper::setAllowedProtocols($filter_protocols);
93 $this->requestStack = $request_stack;
99 public function setContext(SymfonyRequestContext $context) {
100 $this->context = $context;
106 public function getContext() {
107 return $this->context;
113 public function setStrictRequirements($enabled) {
114 // Ignore changes to this.
120 public function isStrictRequirements() {
127 public function getPathFromRoute($name, $parameters = []) {
128 $route = $this->getRoute($name);
129 $name = $this->getRouteDebugMessage($name);
130 $this->processRoute($name, $route, $parameters);
131 $path = $this->getInternalPathFromRoute($name, $route, $parameters);
132 // Router-based paths may have a querystring on them but Drupal paths may
133 // not have one, so remove any ? and anything after it. For generate() this
134 // is handled in processPath().
135 $path = preg_replace('/\?.*/', '', $path);
136 return trim($path, '/');
140 * Substitute the route parameters into the route path.
142 * Note: This code was copied from
143 * \Symfony\Component\Routing\Generator\UrlGenerator::doGenerate() and
144 * shortened by removing code that is not relevant to Drupal or that is
145 * handled separately in ::generateFromRoute(). The Symfony version should be
146 * examined for changes in new Symfony releases.
148 * @param array $variables
149 * The variables form the compiled route, corresponding to slugs in the
151 * @param array $defaults
152 * The defaults from the route.
153 * @param array $tokens
154 * The tokens from the compiled route.
155 * @param array $parameters
156 * The route parameters passed to the generator. Parameters that do not
157 * match any variables will be added to the result as query parameters.
158 * @param array $query_params
159 * Query parameters passed to the generator as $options['query']. This may
160 * be modified if there are extra parameters not used as route variables.
161 * @param string $name
162 * The route name or other identifying string from ::getRouteDebugMessage().
165 * The url path, without any base path, without the query string, not URL
168 * @throws MissingMandatoryParametersException
169 * When some parameters are missing that are mandatory for the route.
170 * @throws InvalidParameterException
171 * When a parameter value for a placeholder is not correct because it does
172 * not match the requirement.
174 protected function doGenerate(array $variables, array $defaults, array $tokens, array $parameters, array &$query_params, $name) {
175 $variables = array_flip($variables);
176 $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
178 // all params must be given
179 if ($diff = array_diff_key($variables, $mergedParams)) {
180 throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
184 // Tokens start from the end of the path and work to the beginning. The
185 // first one or several variable tokens may be optional, but once we find a
186 // supplied token or a static text portion of the path, all remaining
187 // variables up to the start of the path must be supplied to there is no gap.
189 // Structure of $tokens from the compiled route:
190 // If the path is /admin/config/user-interface/shortcut/manage/{shortcut_set}/add-link-inline
191 // [ [ 0 => 'text', 1 => '/add-link-inline' ], [ 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'shortcut_set' ], [ 0 => 'text', 1 => '/admin/config/user-interface/shortcut/manage' ] ]
193 // For a simple fixed path, there is just one token.
194 // If the path is /admin/config
195 // [ [ 0 => 'text', 1 => '/admin/config' ] ]
196 foreach ($tokens as $token) {
197 if ('variable' === $token[0]) {
198 if (!$optional || !array_key_exists($token[3], $defaults) || (isset($mergedParams[$token[3]]) && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]])) {
200 if (!preg_match('#^' . $token[2] . '$#', $mergedParams[$token[3]])) {
201 $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]]);
202 throw new InvalidParameterException($message);
205 $url = $token[1] . $mergedParams[$token[3]] . $url;
211 $url = $token[1] . $url;
220 // Add extra parameters to the query parameters.
221 $query_params += array_diff_key($parameters, $variables, $defaults);
227 * Gets the path of a route.
230 * The route name or other debug message.
231 * @param \Symfony\Component\Routing\Route $route
233 * @param array $parameters
234 * An array of parameters as passed to
235 * \Symfony\Component\Routing\Generator\UrlGeneratorInterface::generate().
236 * @param array $query_params
237 * An array of query string parameter, which will get any extra values from
238 * $parameters merged in.
241 * The URL path corresponding to the route, without the base path, not URL
244 protected function getInternalPathFromRoute($name, SymfonyRoute $route, $parameters = [], &$query_params = []) {
245 // The Route has a cache of its own and is not recompiled as long as it does
247 $compiledRoute = $route->compile();
249 return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $compiledRoute->getTokens(), $parameters, $query_params, $name);
255 public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH) {
256 $options['absolute'] = is_bool($referenceType) ? $referenceType : $referenceType === self::ABSOLUTE_URL;
257 return $this->generateFromRoute($name, $parameters, $options);
263 public function generateFromRoute($name, $parameters = [], $options = [], $collect_bubbleable_metadata = FALSE) {
264 $options += ['prefix' => ''];
265 if (!isset($options['query']) || !is_array($options['query'])) {
266 $options['query'] = [];
269 $route = $this->getRoute($name);
270 $generated_url = $collect_bubbleable_metadata ? new GeneratedUrl() : NULL;
273 if (isset($options['fragment'])) {
274 if (($fragment = trim($options['fragment'])) != '') {
275 $fragment = '#' . $fragment;
279 // Generate a relative URL having no path, just query string and fragment.
280 if ($route->getOption('_no_path')) {
281 $query = $options['query'] ? '?' . UrlHelper::buildQuery($options['query']) : '';
282 $url = $query . $fragment;
283 return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
286 $options += $route->getOption('default_url_options') ?: [];
287 $options += ['prefix' => '', 'path_processing' => TRUE];
289 $name = $this->getRouteDebugMessage($name);
290 $this->processRoute($name, $route, $parameters, $generated_url);
291 $path = $this->getInternalPathFromRoute($name, $route, $parameters, $options['query']);
292 // Outbound path processors might need the route object for the path, e.g.
293 // to get the path pattern.
294 $options['route'] = $route;
295 if ($options['path_processing']) {
296 $path = $this->processPath($path, $options, $generated_url);
298 // The contexts base URL is already encoded
299 // (see Symfony\Component\HttpFoundation\Request).
300 $path = str_replace($this->decodedChars[0], $this->decodedChars[1], rawurlencode($path));
302 // Drupal paths rarely include dots, so skip this processing if possible.
303 if (strpos($path, '/.') !== FALSE) {
304 // the path segments "." and ".." are interpreted as relative reference when
305 // resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
306 // so we need to encode them as they are not used for this purpose here
307 // otherwise we would generate a URI that, when followed by a user agent
308 // (e.g. browser), does not match this route
309 $path = strtr($path, ['/../' => '/%2E%2E/', '/./' => '/%2E/']);
310 if ('/..' === substr($path, -3)) {
311 $path = substr($path, 0, -2) . '%2E%2E';
313 elseif ('/.' === substr($path, -2)) {
314 $path = substr($path, 0, -1) . '%2E';
318 if (!empty($options['prefix'])) {
319 $path = ltrim($path, '/');
320 $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
321 $path = '/' . str_replace('%2F', '/', rawurlencode($prefix)) . $path;
324 $query = $options['query'] ? '?' . UrlHelper::buildQuery($options['query']) : '';
326 // The base_url might be rewritten from the language rewrite in domain mode.
327 if (isset($options['base_url'])) {
328 $base_url = $options['base_url'];
330 if (isset($options['https'])) {
331 if ($options['https'] === TRUE) {
332 $base_url = str_replace('http://', 'https://', $base_url);
334 elseif ($options['https'] === FALSE) {
335 $base_url = str_replace('https://', 'http://', $base_url);
339 $url = $base_url . $path . $query . $fragment;
340 return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
343 $base_url = $this->context->getBaseUrl();
345 $absolute = !empty($options['absolute']);
346 if (!$absolute || !$host = $this->context->getHost()) {
347 $url = $base_url . $path . $query . $fragment;
348 return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
351 // Prepare an absolute URL by getting the correct scheme, host and port from
352 // the request context.
353 if (isset($options['https'])) {
354 $scheme = $options['https'] ? 'https' : 'http';
357 $scheme = $this->context->getScheme();
359 $scheme_req = $route->getSchemes();
360 if ($scheme_req && ($req = $scheme_req[0]) && $scheme !== $req) {
364 if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
365 $port = ':' . $this->context->getHttpPort();
367 elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
368 $port = ':' . $this->context->getHttpsPort();
370 if ($collect_bubbleable_metadata) {
371 $generated_url->addCacheContexts(['url.site']);
373 $url = $scheme . '://' . $host . $port . $base_url . $path . $query . $fragment;
374 return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
378 * Passes the path to a processor manager to allow alterations.
380 protected function processPath($path, &$options = [], BubbleableMetadata $bubbleable_metadata = NULL) {
381 $actual_path = $path === '/' ? $path : rtrim($path, '/');
382 return $this->pathProcessor->processOutbound($actual_path, $options, $this->requestStack->getCurrentRequest(), $bubbleable_metadata);
386 * Passes the route to the processor manager for altering before compilation.
388 * @param string $name
390 * @param \Symfony\Component\Routing\Route $route
391 * The route object to process.
392 * @param array $parameters
393 * An array of parameters to be passed to the route compiler.
394 * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
395 * (optional) Object to collect route processors' bubbleable metadata.
397 protected function processRoute($name, SymfonyRoute $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL) {
398 $this->routeProcessor->processOutbound($name, $route, $parameters, $bubbleable_metadata);
402 * Find the route using the provided route name.
404 * @param string|\Symfony\Component\Routing\Route $name
405 * The route name or a route object.
407 * @return \Symfony\Component\Routing\Route
410 * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
411 * Thrown if there is no route with that name in this repository.
413 * @see \Drupal\Core\Routing\RouteProviderInterface
415 protected function getRoute($name) {
416 if ($name instanceof SymfonyRoute) {
419 elseif (NULL === $route = clone $this->provider->getRouteByName($name)) {
420 throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
428 public function supports($name) {
429 // Support a route object and any string as route name.
430 return is_string($name) || $name instanceof SymfonyRoute;
436 public function getRouteDebugMessage($name, array $parameters = []) {
437 if (is_scalar($name)) {
441 if ($name instanceof SymfonyRoute) {
442 return 'Route with pattern ' . $name->getPath();
445 return serialize($name);