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 // Map from these encoded characters.
70 // Map to these decoded characters.
75 * Constructs a new generator object.
77 * @param \Drupal\Core\Routing\RouteProviderInterface $provider
78 * The route provider to be searched for routes.
79 * @param \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $path_processor
80 * The path processor to convert the system path to one suitable for urls.
81 * @param \Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface $route_processor
82 * The route processor.
83 * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
84 * A request stack object.
85 * @param string[] $filter_protocols
86 * (optional) An array of protocols allowed for URL generation.
88 public function __construct(RouteProviderInterface $provider, OutboundPathProcessorInterface $path_processor, OutboundRouteProcessorInterface $route_processor, RequestStack $request_stack, array $filter_protocols = ['http', 'https']) {
89 $this->provider = $provider;
90 $this->context = new RequestContext();
92 $this->pathProcessor = $path_processor;
93 $this->routeProcessor = $route_processor;
94 UrlHelper::setAllowedProtocols($filter_protocols);
95 $this->requestStack = $request_stack;
101 public function setContext(SymfonyRequestContext $context) {
102 $this->context = $context;
108 public function getContext() {
109 return $this->context;
115 public function setStrictRequirements($enabled) {
116 // Ignore changes to this.
122 public function isStrictRequirements() {
129 public function getPathFromRoute($name, $parameters = []) {
130 $route = $this->getRoute($name);
131 $name = $this->getRouteDebugMessage($name);
132 $this->processRoute($name, $route, $parameters);
133 $path = $this->getInternalPathFromRoute($name, $route, $parameters);
134 // Router-based paths may have a querystring on them but Drupal paths may
135 // not have one, so remove any ? and anything after it. For generate() this
136 // is handled in processPath().
137 $path = preg_replace('/\?.*/', '', $path);
138 return trim($path, '/');
142 * Substitute the route parameters into the route path.
144 * Note: This code was copied from
145 * \Symfony\Component\Routing\Generator\UrlGenerator::doGenerate() and
146 * shortened by removing code that is not relevant to Drupal or that is
147 * handled separately in ::generateFromRoute(). The Symfony version should be
148 * examined for changes in new Symfony releases.
150 * @param array $variables
151 * The variables from the compiled route, corresponding to slugs in the
153 * @param array $defaults
154 * The defaults from the route.
155 * @param array $tokens
156 * The tokens from the compiled route.
157 * @param array $parameters
158 * The route parameters passed to the generator. Parameters that do not
159 * match any variables will be added to the result as query parameters.
160 * @param array $query_params
161 * Query parameters passed to the generator as $options['query']. This may
162 * be modified if there are extra parameters not used as route variables.
163 * @param string $name
164 * The route name or other identifying string from ::getRouteDebugMessage().
167 * The url path, without any base path, without the query string, not URL
170 * @throws MissingMandatoryParametersException
171 * When some parameters are missing that are mandatory for the route.
172 * @throws InvalidParameterException
173 * When a parameter value for a placeholder is not correct because it does
174 * not match the requirement.
176 protected function doGenerate(array $variables, array $defaults, array $tokens, array $parameters, array &$query_params, $name) {
177 $variables = array_flip($variables);
178 $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
180 // all params must be given
181 if ($diff = array_diff_key($variables, $mergedParams)) {
182 throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
186 // Tokens start from the end of the path and work to the beginning. The
187 // first one or several variable tokens may be optional, but once we find a
188 // supplied token or a static text portion of the path, all remaining
189 // variables up to the start of the path must be supplied to there is no gap.
191 // Structure of $tokens from the compiled route:
192 // If the path is /admin/config/user-interface/shortcut/manage/{shortcut_set}/add-link-inline
193 // [ [ 0 => 'text', 1 => '/add-link-inline' ], [ 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'shortcut_set' ], [ 0 => 'text', 1 => '/admin/config/user-interface/shortcut/manage' ] ]
195 // For a simple fixed path, there is just one token.
196 // If the path is /admin/config
197 // [ [ 0 => 'text', 1 => '/admin/config' ] ]
198 foreach ($tokens as $token) {
199 if ('variable' === $token[0]) {
200 if (!$optional || !array_key_exists($token[3], $defaults) || (isset($mergedParams[$token[3]]) && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]])) {
202 if (!preg_match('#^' . $token[2] . '$#', $mergedParams[$token[3]])) {
203 $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]]);
204 throw new InvalidParameterException($message);
207 $url = $token[1] . $mergedParams[$token[3]] . $url;
213 $url = $token[1] . $url;
222 // Add extra parameters to the query parameters.
223 $query_params += array_diff_key($parameters, $variables, $defaults);
229 * Gets the path of a route.
232 * The route name or other debug message.
233 * @param \Symfony\Component\Routing\Route $route
235 * @param array $parameters
236 * An array of parameters as passed to
237 * \Symfony\Component\Routing\Generator\UrlGeneratorInterface::generate().
238 * @param array $query_params
239 * An array of query string parameter, which will get any extra values from
240 * $parameters merged in.
243 * The URL path corresponding to the route, without the base path, not URL
246 protected function getInternalPathFromRoute($name, SymfonyRoute $route, $parameters = [], &$query_params = []) {
247 // The Route has a cache of its own and is not recompiled as long as it does
249 $compiledRoute = $route->compile();
251 return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $compiledRoute->getTokens(), $parameters, $query_params, $name);
257 public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH) {
258 $options['absolute'] = is_bool($referenceType) ? $referenceType : $referenceType === self::ABSOLUTE_URL;
259 return $this->generateFromRoute($name, $parameters, $options);
265 public function generateFromRoute($name, $parameters = [], $options = [], $collect_bubbleable_metadata = FALSE) {
266 $options += ['prefix' => ''];
267 if (!isset($options['query']) || !is_array($options['query'])) {
268 $options['query'] = [];
271 $route = $this->getRoute($name);
272 $generated_url = $collect_bubbleable_metadata ? new GeneratedUrl() : NULL;
275 if (isset($options['fragment'])) {
276 if (($fragment = trim($options['fragment'])) != '') {
277 $fragment = '#' . $fragment;
281 // Generate a relative URL having no path, just query string and fragment.
282 if ($route->getOption('_no_path')) {
283 $query = $options['query'] ? '?' . UrlHelper::buildQuery($options['query']) : '';
284 $url = $query . $fragment;
285 return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
288 $options += $route->getOption('default_url_options') ?: [];
289 $options += ['prefix' => '', 'path_processing' => TRUE];
291 $name = $this->getRouteDebugMessage($name);
292 $this->processRoute($name, $route, $parameters, $generated_url);
293 $path = $this->getInternalPathFromRoute($name, $route, $parameters, $options['query']);
294 // Outbound path processors might need the route object for the path, e.g.
295 // to get the path pattern.
296 $options['route'] = $route;
297 if ($options['path_processing']) {
298 $path = $this->processPath($path, $options, $generated_url);
300 // Ensure the resulting path has at most one leading slash, to prevent it
301 // becoming an external URL without a protocol like //example.com.
302 if (strpos($path, '//') === 0) {
303 $path = '/' . ltrim($path, '/');
305 // The contexts base URL is already encoded
306 // (see Symfony\Component\HttpFoundation\Request).
307 $path = str_replace($this->decodedChars[0], $this->decodedChars[1], rawurlencode($path));
309 // Drupal paths rarely include dots, so skip this processing if possible.
310 if (strpos($path, '/.') !== FALSE) {
311 // the path segments "." and ".." are interpreted as relative reference when
312 // resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
313 // so we need to encode them as they are not used for this purpose here
314 // otherwise we would generate a URI that, when followed by a user agent
315 // (e.g. browser), does not match this route
316 $path = strtr($path, ['/../' => '/%2E%2E/', '/./' => '/%2E/']);
317 if ('/..' === substr($path, -3)) {
318 $path = substr($path, 0, -2) . '%2E%2E';
320 elseif ('/.' === substr($path, -2)) {
321 $path = substr($path, 0, -1) . '%2E';
325 if (!empty($options['prefix'])) {
326 $path = ltrim($path, '/');
327 $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
328 $path = '/' . str_replace('%2F', '/', rawurlencode($prefix)) . $path;
331 $query = $options['query'] ? '?' . UrlHelper::buildQuery($options['query']) : '';
333 // The base_url might be rewritten from the language rewrite in domain mode.
334 if (isset($options['base_url'])) {
335 $base_url = $options['base_url'];
337 if (isset($options['https'])) {
338 if ($options['https'] === TRUE) {
339 $base_url = str_replace('http://', 'https://', $base_url);
341 elseif ($options['https'] === FALSE) {
342 $base_url = str_replace('https://', 'http://', $base_url);
346 $url = $base_url . $path . $query . $fragment;
347 return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
350 $base_url = $this->context->getBaseUrl();
352 $absolute = !empty($options['absolute']);
353 if (!$absolute || !$host = $this->context->getHost()) {
354 $url = $base_url . $path . $query . $fragment;
355 return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
358 // Prepare an absolute URL by getting the correct scheme, host and port from
359 // the request context.
360 if (isset($options['https'])) {
361 $scheme = $options['https'] ? 'https' : 'http';
364 $scheme = $this->context->getScheme();
366 $scheme_req = $route->getSchemes();
367 if ($scheme_req && ($req = $scheme_req[0]) && $scheme !== $req) {
371 if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
372 $port = ':' . $this->context->getHttpPort();
374 elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
375 $port = ':' . $this->context->getHttpsPort();
377 if ($collect_bubbleable_metadata) {
378 $generated_url->addCacheContexts(['url.site']);
380 $url = $scheme . '://' . $host . $port . $base_url . $path . $query . $fragment;
381 return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
385 * Passes the path to a processor manager to allow alterations.
387 protected function processPath($path, &$options = [], BubbleableMetadata $bubbleable_metadata = NULL) {
388 $actual_path = $path === '/' ? $path : rtrim($path, '/');
389 return $this->pathProcessor->processOutbound($actual_path, $options, $this->requestStack->getCurrentRequest(), $bubbleable_metadata);
393 * Passes the route to the processor manager for altering before compilation.
395 * @param string $name
397 * @param \Symfony\Component\Routing\Route $route
398 * The route object to process.
399 * @param array $parameters
400 * An array of parameters to be passed to the route compiler.
401 * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
402 * (optional) Object to collect route processors' bubbleable metadata.
404 protected function processRoute($name, SymfonyRoute $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL) {
405 $this->routeProcessor->processOutbound($name, $route, $parameters, $bubbleable_metadata);
409 * Find the route using the provided route name.
411 * @param string|\Symfony\Component\Routing\Route $name
412 * The route name or a route object.
414 * @return \Symfony\Component\Routing\Route
417 * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
418 * Thrown if there is no route with that name in this repository.
420 * @see \Drupal\Core\Routing\RouteProviderInterface
422 protected function getRoute($name) {
423 if ($name instanceof SymfonyRoute) {
426 elseif (NULL === $route = clone $this->provider->getRouteByName($name)) {
427 throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
435 public function supports($name) {
436 // Support a route object and any string as route name.
437 return is_string($name) || $name instanceof SymfonyRoute;
443 public function getRouteDebugMessage($name, array $parameters = []) {
444 if (is_scalar($name)) {
448 if ($name instanceof SymfonyRoute) {
449 return 'Route with pattern ' . $name->getPath();
452 return serialize($name);