Url.php 29.2 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core;

5
use Drupal\Component\Utility\NestedArray;
6
use Drupal\Component\Utility\UrlHelper;
7
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
8
use Drupal\Core\Routing\RouteMatchInterface;
9
use Drupal\Core\Routing\UrlGeneratorInterface;
10
use Drupal\Core\Session\AccountInterface;
11
use Drupal\Core\Utility\UnroutedUrlAssemblerInterface;
12 13 14 15 16 17
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Defines an object that holds information about a URL.
 */
18 19
class Url {
  use DependencySerializationTrait;
20 21 22 23 24 25 26 27

  /**
   * The URL generator.
   *
   * @var \Drupal\Core\Routing\UrlGeneratorInterface
   */
  protected $urlGenerator;

28 29 30 31 32 33 34
  /**
   * The unrouted URL assembler.
   *
   * @var \Drupal\Core\Utility\UnroutedUrlAssemblerInterface
   */
  protected $urlAssembler;

35 36 37 38 39 40 41
  /**
   * The access manager
   *
   * @var \Drupal\Core\Access\AccessManagerInterface
   */
  protected $accessManager;

42 43 44 45 46 47 48 49 50 51 52 53
  /**
   * The route name.
   *
   * @var string
   */
  protected $routeName;

  /**
   * The route parameters.
   *
   * @var array
   */
54
  protected $routeParameters = [];
55 56 57 58

  /**
   * The URL options.
   *
59 60
   * See \Drupal\Core\Url::fromUri() for details on the options.
   *
61 62
   * @var array
   */
63
  protected $options = [];
64 65

  /**
66
   * Indicates whether this object contains an external URL.
67 68 69 70 71 72
   *
   * @var bool
   */
  protected $external = FALSE;

  /**
73 74 75 76 77 78 79 80
   * Indicates whether this URL is for a URI without a Drupal route.
   *
   * @var bool
   */
  protected $unrouted = FALSE;

  /**
   * The non-route URI.
81
   *
82
   * Only used if self::$unrouted is TRUE.
83 84 85
   *
   * @var string
   */
86
  protected $uri;
87

88
  /**
89
   * Stores the internal path, if already requested by getInternalPath().
90 91 92 93 94
   *
   * @var string
   */
  protected $internalPath;

95 96 97
  /**
   * Constructs a new Url object.
   *
98 99 100 101
   * In most cases, use Url::fromRoute() or Url::fromUri() rather than
   * constructing Url objects directly in order to avoid ambiguity and make your
   * code more self-documenting.
   *
102 103 104 105 106
   * @param string $route_name
   *   The name of the route
   * @param array $route_parameters
   *   (optional) An associative array of parameter names and values.
   * @param array $options
107
   *   See \Drupal\Core\Url::fromUri() for details.
108 109 110 111 112 113
   *
   * @see static::fromRoute()
   * @see static::fromUri()
   *
   * @todo Update this documentation for non-routed URIs in
   *   https://www.drupal.org/node/2346787
114
   */
115
  public function __construct($route_name, $route_parameters = [], $options = []) {
116 117 118 119 120 121
    $this->routeName = $route_name;
    $this->routeParameters = $route_parameters;
    $this->options = $options;
  }

  /**
122
   * Creates a new Url object for a URL that has a Drupal route.
123
   *
124 125
   * This method is for URLs that have Drupal routes (that is, most pages
   * generated by Drupal). For non-routed local URIs relative to the base
126
   * path (like robots.txt) use Url::fromUri() with the base: scheme.
127
   *
128 129 130 131 132
   * @param string $route_name
   *   The name of the route
   * @param array $route_parameters
   *   (optional) An associative array of route parameter names and values.
   * @param array $options
133
   *   See \Drupal\Core\Url::fromUri() for details.
134
   *
135 136
   * @return \Drupal\Core\Url
   *   A new Url object for a routed (internal to Drupal) URL.
137
   *
138 139
   * @see \Drupal\Core\Url::fromUserInput()
   * @see \Drupal\Core\Url::fromUri()
140
   */
141
  public static function fromRoute($route_name, $route_parameters = [], $options = []) {
142 143
    return new static($route_name, $route_parameters, $options);
  }
144

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  /**
   * Creates a new URL object from a route match.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   *
   * @return $this
   */
  public static function fromRouteMatch(RouteMatchInterface $route_match) {
    if ($route_match->getRouteObject()) {
      return new static($route_match->getRouteName(), $route_match->getRawParameters()->all());
    }
    else {
      throw new \InvalidArgumentException('Route required');
    }
  }

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
  /**
   * Creates a Url object for a relative URI reference submitted by user input.
   *
   * Use this method to create a URL for user-entered paths that may or may not
   * correspond to a valid Drupal route.
   *
   * @param string $user_input
   *   User input for a link or path. The first character must be one of the
   *   following characters:
   *   - '/': A path within the current site. This path might be to a Drupal
   *     route (e.g., '/admin'), to a file (e.g., '/README.txt'), or to
   *     something processed by a non-Drupal script (e.g.,
   *     '/not/a/drupal/page'). If the path matches a Drupal route, then the
   *     URL generation will include Drupal's path processors (e.g.,
   *     language-prefixing and aliasing). Otherwise, the URL generation will
   *     just append the passed-in path to Drupal's base path.
   *   - '?': A query string for the current page or resource.
   *   - '#': A fragment (jump-link) on the current page or resource.
   *   This helps reduce ambiguity for user-entered links and paths, and
   *   supports user interfaces where users may normally use auto-completion
   *   to search for existing resources, but also may type one of these
   *   characters to link to (e.g.) a specific path on the site.
   *   (With regard to the URI specification, the user input is treated as a
   *   @link https://tools.ietf.org/html/rfc3986#section-4.2 relative URI reference @endlink
   *   where the relative part is of type
   *   @link https://tools.ietf.org/html/rfc3986#section-3.3 path-abempty @endlink.)
   * @param array $options
   *   (optional) An array of options. See Url::fromUri() for details.
   *
   * @return static
   *   A new Url object based on user input.
   *
   * @throws \InvalidArgumentException
   *   Thrown when the user input does not begin with one of the following
   *   characters: '/', '?', or '#'.
   */
  public static function fromUserInput($user_input, $options = []) {
    // Ensuring one of these initial characters also enforces that what is
    // passed is a relative URI reference rather than an absolute URI,
    // because these are URI reserved characters that a scheme name may not
    // start with.
    if ((strpos($user_input, '/') !== 0) && (strpos($user_input, '#') !== 0) && (strpos($user_input, '?') !== 0)) {
204
      throw new \InvalidArgumentException("The user-entered string '$user_input' must begin with a '/', '?', or '#'.");
205 206 207 208
    }

    // fromUri() requires an absolute URI, so prepend the appropriate scheme
    // name.
209
    return static::fromUri('internal:' . $user_input, $options);
210 211
  }

212
  /**
213
   * Creates a new Url object from a URI.
214
   *
215 216
   * This method is for generating URLs for URIs that:
   * - do not have Drupal routes: both external URLs and unrouted local URIs
217
   *   like base:robots.txt
218 219 220 221 222 223 224
   * - do have a Drupal route but have a custom scheme to simplify linking.
   *   Currently, there is only the entity: scheme (This allows URIs of the
   *   form entity:{entity_type}/{entity_id}. For example: entity:node/1
   *   resolves to the entity.node.canonical route with a node parameter of 1.)
   *
   * For URLs that have Drupal routes (that is, most pages generated by Drupal),
   * use Url::fromRoute().
225 226
   *
   * @param string $uri
227
   *   The URI of the resource including the scheme. For user input that may
228
   *   correspond to a Drupal route, use internal: for the scheme. For paths
229 230 231
   *   that are known not to be handled by the Drupal routing system (such as
   *   static files), use base: for the scheme to get a link relative to the
   *   Drupal base path (like the <base> HTML element). For a link to an entity
232 233 234 235
   *   you may use entity:{entity_type}/{entity_id} URIs. The internal: scheme
   *   should be avoided except when processing actual user input that may or
   *   may not correspond to a Drupal route. Normally use Url::fromRoute() for
   *   code linking to any any Drupal page.
236 237 238 239
   * @param array $options
   *   (optional) An associative array of additional URL options, with the
   *   following elements:
   *   - 'query': An array of query key/value-pairs (without any URL-encoding)
240
   *     to append to the URL.
241 242 243 244 245
   *   - 'fragment': A fragment identifier (named anchor) to append to the URL.
   *     Do not include the leading '#' character.
   *   - 'absolute': Defaults to FALSE. Whether to force the output to be an
   *     absolute link (beginning with http:). Useful for links that will be
   *     displayed outside the site, such as in an RSS feed.
246 247 248
   *   - 'attributes': An associative array of HTML attributes that will be
   *     added to the anchor tag if you use the \Drupal\Core\Link class to make
   *     the link.
249 250 251 252 253
   *   - 'language': An optional language object used to look up the alias
   *     for the URL. If $options['language'] is omitted, it defaults to the
   *     current language for the language type LanguageInterface::TYPE_URL.
   *   - 'https': Whether this URL should point to a secure location. If not
   *     defined, the current scheme is used, so the user stays on HTTP or HTTPS
254
   *     respectively. TRUE enforces HTTPS and FALSE enforces HTTP.
255 256
   *
   * @return \Drupal\Core\Url
257 258
   *   A new Url object with properties depending on the URI scheme. Call the
   *   access() method on this to do access checking.
259 260 261 262
   *
   * @throws \InvalidArgumentException
   *   Thrown when the passed in path has no scheme.
   *
263 264
   * @see \Drupal\Core\Url::fromRoute()
   * @see \Drupal\Core\Url::fromUserInput()
265
   */
266
  public static function fromUri($uri, $options = []) {
267 268 269 270 271
    // parse_url() incorrectly parses base:number/... as hostname:port/...
    // and not the scheme. Prevent that by prefixing the path with a slash.
    if (preg_match('/^base:\d/', $uri)) {
      $uri = str_replace('base:', 'base:/', $uri);
    }
272 273
    $uri_parts = parse_url($uri);
    if ($uri_parts === FALSE) {
274
      throw new \InvalidArgumentException("The URI '$uri' is malformed.");
275
    }
276 277 278 279 280
    // We support protocol-relative URLs.
    if (strpos($uri, '//') === 0) {
      $uri_parts['scheme'] = '';
    }
    elseif (empty($uri_parts['scheme'])) {
281
      throw new \InvalidArgumentException("The URI '$uri' is invalid. You must use a valid URI scheme.");
282
    }
283
    $uri_parts += ['path' => ''];
284 285 286 287
    // Discard empty fragment in $options for consistency with parse_url().
    if (isset($options['fragment']) && strlen($options['fragment']) == 0) {
      unset($options['fragment']);
    }
288 289 290
    // Extract query parameters and fragment and merge them into $uri_options,
    // but preserve the original $options for the fallback case.
    $uri_options = $options;
291
    if (isset($uri_parts['fragment'])) {
292
      $uri_options += ['fragment' => $uri_parts['fragment']];
293
      unset($uri_parts['fragment']);
294
    }
295

296 297 298 299 300 301 302
    if (!empty($uri_parts['query'])) {
      $uri_query = [];
      parse_str($uri_parts['query'], $uri_query);
      $uri_options['query'] = isset($uri_options['query']) ? $uri_options['query'] + $uri_query : $uri_query;
      unset($uri_parts['query']);
    }

303
    if ($uri_parts['scheme'] === 'entity') {
304
      $url = static::fromEntityUri($uri_parts, $uri_options, $uri);
305
    }
306 307
    elseif ($uri_parts['scheme'] === 'internal') {
      $url = static::fromInternalUri($uri_parts, $uri_options);
308 309 310
    }
    elseif ($uri_parts['scheme'] === 'route') {
      $url = static::fromRouteUri($uri_parts, $uri_options, $uri);
311 312
    }
    else {
313
      $url = new static($uri, [], $options);
314 315 316 317 318
      if ($uri_parts['scheme'] !== 'base') {
        $url->external = TRUE;
        $url->setOption('external', TRUE);
      }
      $url->setUnrouted();
319
    }
320 321

    return $url;
322 323
  }

324 325 326
  /**
   * Create a new Url object for entity URIs.
   *
327 328
   * @param array $uri_parts
   *   Parts from an URI of the form entity:{entity_type}/{entity_id} as from
329
   *   parse_url().
330
   * @param array $options
331
   *   An array of options, see \Drupal\Core\Url::fromUri() for details.
332
   * @param string $uri
333
   *   The original entered URI.
334 335 336 337 338 339 340
   *
   * @return \Drupal\Core\Url
   *   A new Url object for an entity's canonical route.
   *
   * @throws \InvalidArgumentException
   *   Thrown if the entity URI is invalid.
   */
341
  protected static function fromEntityUri(array $uri_parts, array $options, $uri) {
342 343
    list($entity_type_id, $entity_id) = explode('/', $uri_parts['path'], 2);
    if ($uri_parts['scheme'] != 'entity' || $entity_id === '') {
344
      throw new \InvalidArgumentException("The entity URI '$uri' is invalid. You must specify the entity id in the URL. e.g., entity:node/1 for loading the canonical path to node entity with id 1.");
345 346
    }

347
    return new static("entity.$entity_type_id.canonical", [$entity_type_id => $entity_id], $options);
348 349
  }

350
  /**
351
   * Creates a new Url object for 'internal:' URIs.
352
   *
353 354
   * Important note: the URI minus the scheme can NOT simply be validated by a
   * \Drupal\Core\Path\PathValidatorInterface implementation. The semantics of
355
   * the 'internal:' URI scheme are different:
356 357 358
   * - PathValidatorInterface accepts paths without a leading slash (e.g.
   *   'node/add') as well as 2 special paths: '<front>' and '<none>', which are
   *   mapped to the correspondingly named routes.
359 360
   * - 'internal:' URIs store paths with a leading slash that represents the
   *   root — i.e. the front page — (e.g. 'internal:/node/add'), and doesn't
361 362
   *   have any exceptions.
   *
363 364 365 366 367 368 369 370 371 372 373 374
   * To clarify, a few examples of path plus corresponding 'internal:' URI:
   * - 'node/add' -> 'internal:/node/add'
   * - 'node/add?foo=bar' -> 'internal:/node/add?foo=bar'
   * - 'node/add#kitten' -> 'internal:/node/add#kitten'
   * - '<front>' -> 'internal:/'
   * - '<front>foo=bar' -> 'internal:/?foo=bar'
   * - '<front>#kitten' -> 'internal:/#kitten'
   * - '<none>' -> 'internal:'
   * - '<none>foo=bar' -> 'internal:?foo=bar'
   * - '<none>#kitten' -> 'internal:#kitten'
   *
   * Therefore, when using a PathValidatorInterface to validate 'internal:'
375
   * URIs, we must map:
376 377 378
   * - 'internal:' (path component is '')  to the special '<none>' path
   * - 'internal:/' (path component is '/') to the special '<front>' path
   * - 'internal:/some-path' (path component is '/some-path') to 'some-path'
379
   *
380
   * @param array $uri_parts
381
   *   Parts from an URI of the form internal:{path} as from parse_url().
382
   * @param array $options
383
   *   An array of options, see \Drupal\Core\Url::fromUri() for details.
384 385
   *
   * @return \Drupal\Core\Url
386
   *   A new Url object for a 'internal:' URI.
387 388 389
   *
   * @throws \InvalidArgumentException
   *   Thrown when the URI's path component doesn't have a leading slash.
390
   */
391
  protected static function fromInternalUri(array $uri_parts, array $options) {
392
    // Both PathValidator::getUrlIfValidWithoutAccessCheck() and 'base:' URIs
393
    // only accept/contain paths without a leading slash, unlike 'internal:'
394 395 396 397 398 399 400 401 402
    // URIs, for which the leading slash means "relative to Drupal root" and
    // "relative to Symfony app root" (just like in Symfony/Drupal 8 routes).
    if (empty($uri_parts['path'])) {
      $uri_parts['path'] = '<none>';
    }
    elseif ($uri_parts['path'] === '/') {
      $uri_parts['path'] = '<front>';
    }
    else {
403
      if ($uri_parts['path'][0] !== '/') {
404
        throw new \InvalidArgumentException("The internal path component '{$uri_parts['path']}' is invalid. Its path component must have a leading slash, e.g. internal:/foo.");
405
      }
406 407
      // Remove the leading slash.
      $uri_parts['path'] = substr($uri_parts['path'], 1);
408 409

      if (UrlHelper::isExternal($uri_parts['path'])) {
410
        throw new \InvalidArgumentException("The internal path component '{$uri_parts['path']}' is external. You are not allowed to specify an external URL together with internal:/.");
411
      }
412 413
    }

414
    $url = \Drupal::pathValidator()
415 416
      ->getUrlIfValidWithoutAccessCheck($uri_parts['path']) ?: static::fromUri('base:' . $uri_parts['path'], $options);
    // Allow specifying additional options.
417 418 419 420 421
    $url->setOptions($options + $url->getOptions());

    return $url;
  }

422 423 424 425 426 427 428 429
  /**
   * Creates a new Url object for 'route:' URIs.
   *
   * @param array $uri_parts
   *   Parts from an URI of the form route:{route_name};{route_parameters} as
   *   from parse_url(), where the path is the route name optionally followed by
   *   a ";" followed by route parameters in key=value format with & separators.
   * @param array $options
430
   *   An array of options, see \Drupal\Core\Url::fromUri() for details.
431 432 433 434 435 436 437 438 439 440 441 442 443
   * @param string $uri
   *   The original passed in URI.
   *
   * @return \Drupal\Core\Url
   *   A new Url object for a 'route:' URI.
   *
   * @throws \InvalidArgumentException
   *   Thrown when the route URI does not have a route name.
   */
  protected static function fromRouteUri(array $uri_parts, array $options, $uri) {
    $route_parts = explode(';', $uri_parts['path'], 2);
    $route_name = $route_parts[0];
    if ($route_name === '') {
444
      throw new \InvalidArgumentException("The route URI '$uri' is invalid. You must have a route name in the URI. e.g., route:system.admin");
445 446 447 448 449 450 451 452 453
    }
    $route_parameters = [];
    if (!empty($route_parts[1])) {
      parse_str($route_parts[1], $route_parameters);
    }

    return new static($route_name, $route_parameters, $options);
  }

454
  /**
455 456 457 458 459 460 461 462 463
   * Returns the Url object matching a request.
   *
   * SECURITY NOTE: The request path is not checked to be valid and accessible
   * by the current user to allow storing and reusing Url objects by different
   * users. The 'path.validator' service getUrlIfValid() method should be used
   * instead of this one if validation and access check is desired. Otherwise,
   * 'access_manager' service checkNamedRoute() method should be used on the
   * router name and parameters stored in the Url object returned by this
   * method.
464 465 466 467 468
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   A request object.
   *
   * @return static
469 470 471
   *   A Url object. Warning: the object is created even if the current user
   *   would get an access denied running the same request via the normal page
   *   flow.
472 473 474 475 476
   *
   * @throws \Drupal\Core\Routing\MatchingRouteNotFoundException
   *   Thrown when the request cannot be matched.
   */
  public static function createFromRequest(Request $request) {
477 478 479
    // We use the router without access checks because URL objects might be
    // created and stored for different users.
    $result = \Drupal::service('router.no_access_checks')->matchRequest($request);
480 481 482 483 484 485
    $route_name = $result[RouteObjectInterface::ROUTE_NAME];
    $route_parameters = $result['_raw_variables']->all();
    return new static($route_name, $route_parameters);
  }

  /**
486
   * Sets this Url to encapsulate an unrouted URI.
487 488 489
   *
   * @return $this
   */
490 491 492 493 494
  protected function setUnrouted() {
    $this->unrouted = TRUE;
    // What was passed in as the route name is actually the URI.
    // @todo Consider fixing this in https://www.drupal.org/node/2346787.
    $this->uri = $this->routeName;
495
    // Set empty route name and parameters.
496
    $this->routeName = NULL;
497
    $this->routeParameters = [];
498
    return $this;
499 500
  }

501
  /**
502
   * Generates a URI string that represents the data in the Url object.
503 504
   *
   * The URI will typically have the scheme of route: even if the object was
505
   * constructed using an entity: or internal: scheme. A internal: URI that
506 507
   * does not match a Drupal route with be returned here with the base: scheme,
   * and external URLs will be returned in their original form.
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
   *
   * @return string
   *   A URI representation of the Url object data.
   */
  public function toUriString() {
    if ($this->isRouted()) {
      $uri = 'route:' . $this->routeName;
      if ($this->routeParameters) {
        $uri .= ';' . UrlHelper::buildQuery($this->routeParameters);
      }
    }
    else {
      $uri = $this->uri;
    }
    $query = !empty($this->options['query']) ? ('?' . UrlHelper::buildQuery($this->options['query'])) : '';
523
    $fragment = isset($this->options['fragment']) && strlen($this->options['fragment']) ? '#' . $this->options['fragment'] : '';
524 525 526
    return $uri . $query . $fragment;
  }

527 528 529 530 531 532 533 534 535
  /**
   * Indicates if this Url is external.
   *
   * @return bool
   */
  public function isExternal() {
    return $this->external;
  }

536 537 538 539 540 541 542 543 544
  /**
   * Indicates if this Url has a Drupal route.
   *
   * @return bool
   */
  public function isRouted() {
    return !$this->unrouted;
  }

545 546 547 548
  /**
   * Returns the route name.
   *
   * @return string
549 550
   *
   * @throws \UnexpectedValueException.
551
   *   If this is a URI with no corresponding route.
552 553
   */
  public function getRouteName() {
554
    if ($this->unrouted) {
555 556 557
      throw new \UnexpectedValueException('External URLs do not have an internal route name.');
    }

558 559 560 561 562 563 564
    return $this->routeName;
  }

  /**
   * Returns the route parameters.
   *
   * @return array
565 566
   *
   * @throws \UnexpectedValueException.
567
   *   If this is a URI with no corresponding route.
568 569
   */
  public function getRouteParameters() {
570
    if ($this->unrouted) {
571 572 573
      throw new \UnexpectedValueException('External URLs do not have internal route parameters.');
    }

574 575 576 577 578 579 580 581 582 583
    return $this->routeParameters;
  }

  /**
   * Sets the route parameters.
   *
   * @param array $parameters
   *   The array of parameters.
   *
   * @return $this
584 585 586
   *
   * @throws \UnexpectedValueException.
   *   If this is a URI with no corresponding route.
587 588
   */
  public function setRouteParameters($parameters) {
589 590
    if ($this->unrouted) {
      throw new \UnexpectedValueException('External URLs do not have route parameters.');
591 592 593 594 595 596 597 598 599 600 601 602 603 604
    }
    $this->routeParameters = $parameters;
    return $this;
  }

  /**
   * Sets a specific route parameter.
   *
   * @param string $key
   *   The key of the route parameter.
   * @param mixed $value
   *   The route parameter.
   *
   * @return $this
605 606 607
   *
   * @throws \UnexpectedValueException.
   *   If this is a URI with no corresponding route.
608 609
   */
  public function setRouteParameter($key, $value) {
610 611
    if ($this->unrouted) {
      throw new \UnexpectedValueException('External URLs do not have route parameters.');
612 613 614 615 616 617 618 619 620
    }
    $this->routeParameters[$key] = $value;
    return $this;
  }

  /**
   * Returns the URL options.
   *
   * @return array
621 622
   *   The array of options. See \Drupal\Core\Url::fromUri() for details on what
   *   it contains.
623 624 625 626 627 628 629 630
   */
  public function getOptions() {
    return $this->options;
  }

  /**
   * Gets a specific option.
   *
631 632
   * See \Drupal\Core\Url::fromUri() for details on the options.
   *
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
   * @param string $name
   *   The name of the option.
   *
   * @return mixed
   *   The value for a specific option, or NULL if it does not exist.
   */
  public function getOption($name) {
    if (!isset($this->options[$name])) {
      return NULL;
    }

    return $this->options[$name];
  }

  /**
   * Sets the URL options.
   *
   * @param array $options
651 652
   *   The array of options. See \Drupal\Core\Url::fromUri() for details on what
   *   it contains.
653 654 655 656 657 658 659 660 661 662 663
   *
   * @return $this
   */
  public function setOptions($options) {
    $this->options = $options;
    return $this;
  }

  /**
   * Sets a specific option.
   *
664 665
   * See \Drupal\Core\Url::fromUri() for details on the options.
   *
666 667 668 669 670 671 672 673 674 675 676 677
   * @param string $name
   *   The name of the option.
   * @param mixed $value
   *   The option value.
   *
   * @return $this
   */
  public function setOption($name, $value) {
    $this->options[$name] = $value;
    return $this;
  }

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
  /**
   * Merges the URL options with any currently set.
   *
   * In the case of conflict with existing options, the new options will replace
   * the existing options.
   *
   * @param array $options
   *   The array of options. See \Drupal\Core\Url::fromUri() for details on what
   *   it contains.
   *
   * @return $this
   */
  public function mergeOptions($options) {
    $this->options = NestedArray::mergeDeep($this->options, $options);
    return $this;
  }

695
  /**
696
   * Returns the URI value for this Url object.
697
   *
698
   * Only to be used if self::$unrouted is TRUE.
699 700
   *
   * @return string
701
   *   A URI not connected to a route. May be an external URL.
702 703
   *
   * @throws \UnexpectedValueException
704
   *   Thrown when the URI was requested for a routed URL.
705
   */
706 707 708
  public function getUri() {
    if (!$this->unrouted) {
      throw new \UnexpectedValueException('This URL has a Drupal route, so the canonical form is not a URI.');
709 710
    }

711
    return $this->uri;
712 713
  }

714
  /**
715
   * Sets the value of the absolute option for this Url.
716 717 718 719 720 721 722 723 724 725 726 727
   *
   * @param bool $absolute
   *   (optional) Whether to make this Url absolute or not. Defaults to TRUE.
   *
   * @return $this
   */
  public function setAbsolute($absolute = TRUE) {
    $this->options['absolute'] = $absolute;
    return $this;
  }

  /**
728 729 730 731 732 733
   * Generates the string URL representation for this Url object.
   *
   * For an external URL, the string will contain the input plus any query
   * string or fragment specified by the options array.
   *
   * If this Url object was constructed from a Drupal route or from an internal
734
   * URI (URIs using the internal:, base:, or entity: schemes), the returned
735 736 737 738
   * string will either be a relative URL like /node/1 or an absolute URL like
   * http://example.com/node/1 depending on the options array, plus any
   * specified query string or fragment.
   *
739
   * @param bool $collect_bubbleable_metadata
740
   *   (optional) Defaults to FALSE. When TRUE, both the generated URL and its
741
   *   associated bubbleable metadata are returned.
742 743
   *
   * @return string|\Drupal\Core\GeneratedUrl
744
   *   A string URL.
745 746
   *   When $collect_bubbleable_metadata is TRUE, a GeneratedUrl object is
   *   returned, containing the generated URL plus bubbleable metadata.
747
   */
748
  public function toString($collect_bubbleable_metadata = FALSE) {
749
    if ($this->unrouted) {
750
      return $this->unroutedUrlAssembler()->assemble($this->getUri(), $this->getOptions(), $collect_bubbleable_metadata);
751 752
    }

753
    return $this->urlGenerator()->generateFromRoute($this->getRouteName(), $this->getRouteParameters(), $this->getOptions(), $collect_bubbleable_metadata);
754 755 756 757 758 759 760 761 762
  }

  /**
   * Returns the route information for a render array.
   *
   * @return array
   *   An associative array suitable for a render array.
   */
  public function toRenderArray() {
763 764 765 766 767 768
    $render_array = [
      '#url' => $this,
      '#options' => $this->getOptions(),
    ];
    if (!$this->unrouted) {
      $render_array['#access_callback'] = [get_class(), 'renderAccess'];
769
    }
770
    return $render_array;
771 772 773
  }

  /**
774
   * Returns the internal path (system path) for this route.
775 776 777 778 779
   *
   * This path will not include any prefixes, fragments, or query strings.
   *
   * @return string
   *   The internal path for this route.
780 781
   *
   * @throws \UnexpectedValueException.
782
   *   If this is a URI with no corresponding system path.
783 784
   */
  public function getInternalPath() {
785 786
    if ($this->unrouted) {
      throw new \UnexpectedValueException('Unrouted URIs do not have internal representations.');
787
    }
788 789 790 791 792

    if (!isset($this->internalPath)) {
      $this->internalPath = $this->urlGenerator()->getPathFromRoute($this->getRouteName(), $this->getRouteParameters());
    }
    return $this->internalPath;
793 794
  }

795 796 797 798 799 800 801 802 803 804 805 806 807
  /**
   * Checks this Url object against applicable access check services.
   *
   * Determines whether the route is accessible or not.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   (optional) Run access checks for this account. Defaults to the current
   *   user.
   *
   * @return bool
   *   Returns TRUE if the user has access to the url, otherwise FALSE.
   */
  public function access(AccountInterface $account = NULL) {
808 809 810 811
    if ($this->isRouted()) {
      return $this->accessManager()->checkNamedRoute($this->getRouteName(), $this->getRouteParameters(), $account);
    }
    return TRUE;
812 813 814 815 816 817 818 819 820 821 822 823
  }

  /**
   * Checks a Url render element against applicable access check services.
   *
   * @param array $element
   *   A render element as returned from \Drupal\Core\Url::toRenderArray().
   *
   * @return bool
   *   Returns TRUE if the current user has access to the url, otherwise FALSE.
   */
  public static function renderAccess(array $element) {
824
    return $element['#url']->access();
825 826 827 828 829 830 831 832 833 834 835 836
  }

  /**
   * @return \Drupal\Core\Access\AccessManagerInterface
   */
  protected function accessManager() {
    if (!isset($this->accessManager)) {
      $this->accessManager = \Drupal::service('access_manager');
    }
    return $this->accessManager;
  }

837 838 839 840 841 842 843 844 845 846 847 848 849
  /**
   * Gets the URL generator.
   *
   * @return \Drupal\Core\Routing\UrlGeneratorInterface
   *   The URL generator.
   */
  protected function urlGenerator() {
    if (!$this->urlGenerator) {
      $this->urlGenerator = \Drupal::urlGenerator();
    }
    return $this->urlGenerator;
  }

850 851 852 853 854 855 856 857 858 859 860 861 862
  /**
   * Gets the unrouted URL assembler for non-Drupal URLs.
   *
   * @return \Drupal\Core\Utility\UnroutedUrlAssemblerInterface
   *   The unrouted URL assembler.
   */
  protected function unroutedUrlAssembler() {
    if (!$this->urlAssembler) {
      $this->urlAssembler = \Drupal::service('unrouted_url_assembler');
    }
    return $this->urlAssembler;
  }

863 864 865
  /**
   * Sets the URL generator.
   *
866
   * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
867
   *   (optional) The URL generator, specify NULL to reset it.
868 869 870
   *
   * @return $this
   */
871
  public function setUrlGenerator(UrlGeneratorInterface $url_generator = NULL) {
872
    $this->urlGenerator = $url_generator;
873
    $this->internalPath = NULL;
874 875 876
    return $this;
  }

877 878 879
  /**
   * Sets the unrouted URL assembler.
   *
880
   * @param \Drupal\Core\Utility\UnroutedUrlAssemblerInterface $url_assembler
881 882 883 884 885 886 887 888 889
   *   The unrouted URL assembler.
   *
   * @return $this
   */
  public function setUnroutedUrlAssembler(UnroutedUrlAssemblerInterface $url_assembler) {
    $this->urlAssembler = $url_assembler;
    return $this;
  }

890
}