class Url implements TrustedCallbackInterface (View source)

Defines an object that holds information about a URL.

In most cases, these should be created with the following methods:

  • \Drupal\Core\Url::fromRoute()
  • \Drupal\Core\Url::fromRouteMatch()
  • \Drupal\Core\Url::fromUri()
  • \Drupal\Core\Url::fromUserInput()

Traits

Provides dependency injection friendly methods for serialization.

Properties

protected array $_serviceIds

An array of service IDs keyed by property name used for serialization.

from  DependencySerializationTrait
protected array $_entityStorages

An array of entity type IDs keyed by the property name of their storages.

from  DependencySerializationTrait
protected UrlGeneratorInterface $urlGenerator

The URL generator.

protected UnroutedUrlAssemblerInterface $urlAssembler

The unrouted URL assembler.

protected AccessManagerInterface $accessManager

The access manager.

protected string $routeName

The route name.

protected array $routeParameters

The route parameters.

protected array $options

The URL options.

protected bool $external

Indicates whether this object contains an external URL.

protected bool $unrouted

Indicates whether this URL is for a URI without a Drupal route.

protected string $uri

The non-route URI.

protected string $internalPath

Stores the internal path, if already requested by getInternalPath().

Methods

__sleep()

{@inheritdoc}

__wakeup()

{@inheritdoc}

__construct(string $route_name, array $route_parameters = [], array $options = [])

Constructs a new Url object.

static Url
fromRoute(string $route_name, array $route_parameters = [], array $options = [])

Creates a new Url object for a URL that has a Drupal route.

static Url
fromRouteMatch(RouteMatchInterface $route_match)

Creates a new URL object from a route match.

static Url
fromUserInput(string $user_input, array $options = [])

Creates a Url object for a relative URI reference submitted by user input.

static Url
fromUri(string $uri, array $options = [])

Creates a new Url object from a URI.

static Url
fromEntityUri(array $uri_parts, array $options, string $uri)

Create a new Url object for entity URIs.

static Url
fromInternalUri(array $uri_parts, array $options)

Creates a new Url object for 'internal:' URIs.

static Url
fromRouteUri(array $uri_parts, array $options, string $uri)

Creates a new Url object for 'route:' URIs.

static Url
createFromRequest(Request $request)

Returns the Url object matching a request.

$this
setUnrouted()

Sets this Url to encapsulate an unrouted URI.

string
toUriString()

Generates a URI string that represents the data in the Url object.

bool
isExternal()

Indicates if this Url is external.

bool
isRouted()

Indicates if this Url has a Drupal route.

string
getRouteName()

Returns the route name.

array
getRouteParameters()

Returns the route parameters.

$this
setRouteParameters(array $parameters)

Sets the route parameters.

$this
setRouteParameter(string $key, mixed $value)

Sets a specific route parameter.

array
getOptions()

Returns the URL options.

mixed
getOption(string $name)

Gets a specific option.

$this
setOptions(array $options)

Sets the URL options.

$this
setOption(string $name, mixed $value)

Sets a specific option.

$this
mergeOptions(array $options)

Merges the URL options with any currently set.

string
getUri()

Returns the URI value for this Url object.

$this
setAbsolute(bool $absolute = TRUE)

Sets the value of the absolute option for this Url.

string|GeneratedUrl
toString(bool $collect_bubbleable_metadata = FALSE)

Generates the string URL representation for this Url object.

array
toRenderArray()

Returns the route information for a render array.

string
getInternalPath()

Returns the internal path (system path) for this route.

access(AccountInterface $account = NULL, bool $return_as_object = FALSE)

Checks this Url object against applicable access check services.

static bool
renderAccess(array $element)

Checks a Url render element against applicable access check services.

urlGenerator()

Gets the URL generator.

unroutedUrlAssembler()

Gets the unrouted URL assembler for non-Drupal URLs.

$this
setUrlGenerator(UrlGeneratorInterface $url_generator = NULL)

Sets the URL generator.

$this
setUnroutedUrlAssembler(UnroutedUrlAssemblerInterface $url_assembler)

Sets the unrouted URL assembler.

static string[]
trustedCallbacks()

Lists the trusted callbacks provided by the implementing class.

Details

__sleep()

{@inheritdoc}

__wakeup()

{@inheritdoc}

__construct(string $route_name, array $route_parameters = [], array $options = [])

Constructs a new Url object.

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.

Update this documentation for non-routed URIs in https://www.drupal.org/node/2346787

Parameters

string $route_name

The name of the route

array $route_parameters

(optional) An associative array of parameter names and values.

array $options

See \Drupal\Core\Url::fromUri() for details.

See also

\Drupal\Core\static::fromRoute()
\Drupal\Core\static::fromUri()

static Url fromRoute(string $route_name, array $route_parameters = [], array $options = [])

Creates a new Url object for a URL that has a Drupal route.

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 path (like robots.txt) use Url::fromUri() with the base: scheme.

Parameters

string $route_name

The name of the route

array $route_parameters

(optional) An associative array of route parameter names and values.

array $options

See \Drupal\Core\Url::fromUri() for details.

Return Value

Url

A new Url object for a routed (internal to Drupal) URL.

See also

Url::fromUserInput
Url::fromUri

static Url fromRouteMatch(RouteMatchInterface $route_match)

Creates a new URL object from a route match.

Parameters

RouteMatchInterface $route_match

The route match.

Return Value

Url

static Url fromUserInput(string $user_input, array $options = [])

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.

Parameters

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.)
array $options

(optional) An array of options. See Url::fromUri() for details.

Return Value

Url

A new Url object based on user input.

Exceptions

InvalidArgumentException

static Url fromUri(string $uri, array $options = [])

Creates a new Url object from a URI.

This method is for generating URLs for URIs that:

  • do not have Drupal routes: both external URLs and unrouted local URIs like base:robots.txt
  • 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().

Parameters

string $uri

The URI of the resource including the scheme. For user input that may correspond to a Drupal route, use internal: for the scheme. For paths 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 HTML element). For a link to an entity 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 Drupal page.

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) to append to the URL.
  • '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.
  • '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.
  • '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 respectively. TRUE enforces HTTPS and FALSE enforces HTTP.

Return Value

Url

A new Url object with properties depending on the URI scheme. Call the access() method on this to do access checking.

Exceptions

InvalidArgumentException

See also

Url::fromRoute
Url::fromUserInput

static protected Url fromEntityUri(array $uri_parts, array $options, string $uri)

Create a new Url object for entity URIs.

Parameters

array $uri_parts

Parts from a URI of the form entity:{entity_type}/{entity_id} as from parse_url().

array $options

An array of options, see \Drupal\Core\Url::fromUri() for details.

string $uri

The original entered URI.

Return Value

Url

A new Url object for an entity's canonical route.

Exceptions

InvalidArgumentException

static protected Url fromInternalUri(array $uri_parts, array $options)

Creates a new Url object for 'internal:' URIs.

Important note: the URI minus the scheme can NOT simply be validated by a \Drupal\Core\Path\PathValidatorInterface implementation. The semantics of the 'internal:' URI scheme are different:

  • PathValidatorInterface accepts paths without a leading slash (e.g. 'node/add') as well as 2 special paths: '' and '', which are mapped to the correspondingly named routes.
  • '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 have any exceptions.

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'
  • '' -> 'internal:/'
  • 'foo=bar' -> 'internal:/?foo=bar'
  • '#kitten' -> 'internal:/#kitten'
  • '' -> 'internal:'
  • 'foo=bar' -> 'internal:?foo=bar'
  • '#kitten' -> 'internal:#kitten'

Therefore, when using a PathValidatorInterface to validate 'internal:' URIs, we must map:

  • 'internal:' (path component is '') to the special '' path
  • 'internal:/' (path component is '/') to the special '' path
  • 'internal:/some-path' (path component is '/some-path') to 'some-path'

Parameters

array $uri_parts

Parts from a URI of the form internal:{path} as from parse_url().

array $options

An array of options, see \Drupal\Core\Url::fromUri() for details.

Return Value

Url

A new Url object for an 'internal:' URI.

Exceptions

InvalidArgumentException

static protected Url fromRouteUri(array $uri_parts, array $options, string $uri)

Creates a new Url object for 'route:' URIs.

Parameters

array $uri_parts

Parts from a 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.

array $options

An array of options, see \Drupal\Core\Url::fromUri() for details.

string $uri

The original passed in URI.

Return Value

Url

A new Url object for a 'route:' URI.

Exceptions

InvalidArgumentException

static Url createFromRequest(Request $request)

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.

Parameters

Request $request

A request object.

Return Value

Url

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.

Exceptions

MatchingRouteNotFoundException

protected $this setUnrouted()

Sets this Url to encapsulate an unrouted URI.

Return Value

$this

string toUriString()

Generates a URI string that represents the data in the Url object.

The URI will typically have the scheme of route: even if the object was constructed using an entity: or internal: scheme. An internal: URI that does not match a Drupal route with be returned here with the base: scheme, and external URLs will be returned in their original form.

Return Value

string

A URI representation of the Url object data.

bool isExternal()

Indicates if this Url is external.

Return Value

bool

bool isRouted()

Indicates if this Url has a Drupal route.

Return Value

bool

string getRouteName()

Returns the route name.

Return Value

string

Exceptions

UnexpectedValueException. If this is a URI with no corresponding route.

array getRouteParameters()

Returns the route parameters.

Return Value

array

Exceptions

UnexpectedValueException. If this is a URI with no corresponding route.

$this setRouteParameters(array $parameters)

Sets the route parameters.

Parameters

array $parameters

The array of parameters.

Return Value

$this

Exceptions

UnexpectedValueException. If this is a URI with no corresponding route.

$this setRouteParameter(string $key, mixed $value)

Sets a specific route parameter.

Parameters

string $key

The key of the route parameter.

mixed $value

The route parameter.

Return Value

$this

Exceptions

UnexpectedValueException. If this is a URI with no corresponding route.

array getOptions()

Returns the URL options.

Return Value

array

The array of options. See \Drupal\Core\Url::fromUri() for details on what it contains.

mixed getOption(string $name)

Gets a specific option.

See \Drupal\Core\Url::fromUri() for details on the options.

Parameters

string $name

The name of the option.

Return Value

mixed

The value for a specific option, or NULL if it does not exist.

$this setOptions(array $options)

Sets the URL options.

Parameters

array $options

The array of options. See \Drupal\Core\Url::fromUri() for details on what it contains.

Return Value

$this

$this setOption(string $name, mixed $value)

Sets a specific option.

See \Drupal\Core\Url::fromUri() for details on the options.

Parameters

string $name

The name of the option.

mixed $value

The option value.

Return Value

$this

$this mergeOptions(array $options)

Merges the URL options with any currently set.

In the case of conflict with existing options, the new options will replace the existing options.

Parameters

array $options

The array of options. See \Drupal\Core\Url::fromUri() for details on what it contains.

Return Value

$this

string getUri()

Returns the URI value for this Url object.

Only to be used if self::$unrouted is TRUE.

Return Value

string

A URI not connected to a route. May be an external URL.

Exceptions

UnexpectedValueException

$this setAbsolute(bool $absolute = TRUE)

Sets the value of the absolute option for this Url.

Parameters

bool $absolute

(optional) Whether to make this Url absolute or not. Defaults to TRUE.

Return Value

$this

string|GeneratedUrl toString(bool $collect_bubbleable_metadata = FALSE)

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 URI (URIs using the internal:, base:, or entity: schemes), the returned 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.

Parameters

bool $collect_bubbleable_metadata

(optional) Defaults to FALSE. When TRUE, both the generated URL and its associated bubbleable metadata are returned.

Return Value

string|GeneratedUrl

A string URL. When $collect_bubbleable_metadata is TRUE, a GeneratedUrl object is returned, containing the generated URL plus bubbleable metadata.

array toRenderArray()

Returns the route information for a render array.

Return Value

array

An associative array suitable for a render array.

string getInternalPath()

Returns the internal path (system path) for this route.

This path will not include any prefixes, fragments, or query strings.

Return Value

string

The internal path for this route.

Exceptions

UnexpectedValueException. If this is a URI with no corresponding system path.

bool|AccessResultInterface access(AccountInterface $account = NULL, bool $return_as_object = FALSE)

Checks this Url object against applicable access check services.

Determines whether the route is accessible or not.

Parameters

AccountInterface $account

(optional) Run access checks for this account. NULL for the current user.

bool $return_as_object

(optional) Defaults to FALSE.

Return Value

bool|AccessResultInterface

The access result. Returns a boolean if $return_as_object is FALSE (this is the default) and otherwise an AccessResultInterface object. When a boolean is returned, the result of AccessInterface::isAllowed() is returned, i.e. TRUE means access is explicitly allowed, FALSE means access is either explicitly forbidden or "no opinion".

static bool renderAccess(array $element)

Checks a Url render element against applicable access check services.

Parameters

array $element

A render element as returned from \Drupal\Core\Url::toRenderArray().

Return Value

bool

Returns TRUE if the current user has access to the url, otherwise FALSE.

protected AccessManagerInterface accessManager()

No description

Return Value

AccessManagerInterface

protected UrlGeneratorInterface urlGenerator()

Gets the URL generator.

Return Value

UrlGeneratorInterface

The URL generator.

protected UnroutedUrlAssemblerInterface unroutedUrlAssembler()

Gets the unrouted URL assembler for non-Drupal URLs.

Return Value

UnroutedUrlAssemblerInterface

The unrouted URL assembler.

$this setUrlGenerator(UrlGeneratorInterface $url_generator = NULL)

Sets the URL generator.

Parameters

UrlGeneratorInterface $url_generator

(optional) The URL generator, specify NULL to reset it.

Return Value

$this

$this setUnroutedUrlAssembler(UnroutedUrlAssemblerInterface $url_assembler)

Sets the unrouted URL assembler.

Parameters

UnroutedUrlAssemblerInterface $url_assembler

The unrouted URL assembler.

Return Value

$this

static string[] trustedCallbacks()

Lists the trusted callbacks provided by the implementing class.

Trusted callbacks are public methods on the implementing class and can be invoked via \Drupal\Core\Security\DoTrustedCallbackTrait::doTrustedCallback().

Return Value

string[]

List of method names implemented by the class that can be used as trusted callbacks.