Drupal 8  8.0.2
Token Class Reference

Public Member Functions

 __construct (ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, CacheTagsInvalidatorInterface $cache_tags_invalidator, RendererInterface $renderer)
 
 replace ($text, array $data=array(), array $options=array(), BubbleableMetadata $bubbleable_metadata=NULL)
 
 scan ($text)
 
 generate ($type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata)
 
 findWithPrefix (array $tokens, $prefix, $delimiter= ':')
 
 getInfo ()
 
 setInfo (array $tokens)
 
 resetInfo ()
 

Data Fields

const TOKEN_INFO_CACHE_TAG = 'token_info'
 

Protected Attributes

 $cache
 
 $languageManager
 
 $tokenInfo
 
 $moduleHandler
 
 $cacheTagsInvalidator
 
 $renderer
 

Detailed Description

Drupal placeholder/token replacement system.

API functions for replacing placeholders in text with meaningful values.

For example: When configuring automated emails, an administrator enters standard text for the email. Variables like the title of a node and the date the email was sent can be entered as placeholders like [node:title] and [date:short]. When a Drupal module prepares to send the email, it can call the Token::replace() function, passing in the text. The token system will scan the text for placeholder tokens, give other modules an opportunity to replace them with meaningful text, then return the final product to the original module.

Tokens follow the form: [$type:$name], where $type is a general class of tokens like 'node', 'user', or 'comment' and $name is the name of a given placeholder. For example, [node:title] or [node:created:since].

In addition to raw text containing placeholders, modules may pass in an array of objects to be used when performing the replacement. The objects should be keyed by the token type they correspond to. For example:

// Load a node and a user, then replace tokens in the text.
$text = 'On [date:short], [user:name] read [node:title].';
$node = Node::load(1);
$user = User::load(1);
// [date:...] tokens use the current date automatically.
$data = array('node' => $node, 'user' => $user);
return Token::replace($text, $data);

Some tokens may be chained in the form of [$type:$pointer:$name], where $type is a normal token type, $pointer is a reference to another token type, and $name is the name of a given placeholder. For example, [node:author:mail]. In that example, 'author' is a pointer to the 'user' account that created the node, and 'mail' is a placeholder available for any 'user'.

See Also
Token::replace()
hook_tokens()
hook_token_info()

Constructor & Destructor Documentation

__construct ( ModuleHandlerInterface  $module_handler,
CacheBackendInterface  $cache,
LanguageManagerInterface  $language_manager,
CacheTagsInvalidatorInterface  $cache_tags_invalidator,
RendererInterface  $renderer 
)

Constructs a new class instance.

Parameters
\Drupal\Core\Extension\ModuleHandlerInterface$module_handlerThe module handler.
\Drupal\Core\Cache\CacheBackendInterface$cacheThe token cache.
\Drupal\Core\Language\LanguageManagerInterface$language_managerThe language manager.
\Drupal\Core\Cache\CacheTagsInvalidatorInterface$cache_tags_invalidatorThe cache tags invalidator.
\Drupal\Core\Render\RendererInterface$rendererThe renderer.

References Drupal\cache(), Drupal\languageManager(), and Drupal\moduleHandler().

Here is the call graph for this function:

Member Function Documentation

findWithPrefix ( array  $tokens,
  $prefix,
  $delimiter = ':' 
)

Returns a list of tokens that begin with a specific prefix.

Used to extract a group of 'chained' tokens (such as [node:author:name]) from the full list of tokens found in text. For example:

$data = array(
'author:name' => '[node:author:name]',
'title' => '[node:title]',
'created' => '[node:created]',
);
$results = Token::findWithPrefix($data, 'author');
$results == array('name' => '[node:author:name]');
Parameters
array$tokensA keyed array of tokens, and their original raw form in the source text.
string$prefixA textual string to be matched at the beginning of the token.
string$delimiter(optional) A string containing the character that separates the prefix from the rest of the token. Defaults to ':'.
Returns
array An associative array of discovered tokens, with the prefix and delimiter stripped from the key.
generate (   $type,
array  $tokens,
array  $data,
array  $options,
BubbleableMetadata  $bubbleable_metadata 
)

Generates replacement values for a list of tokens.

Parameters
string$typeThe type of token being replaced. 'node', 'user', and 'date' are common.
array$tokensAn array of tokens to be replaced, keyed by the literal text of the token as it appeared in the source text.
array$dataAn array of keyed objects. For simple replacement scenarios: 'node', 'user', and others are common keys, with an accompanying node or user object being the value. Some token types, like 'site', do not require any explicit information from $data and can be replaced even if it is empty.
array$optionsA keyed array of settings and flags to control the token replacement process. Supported options are:
  • langcode: A language code to be used when generating locale-sensitive tokens.
  • callback: A callback function that will be used to post-process the array of token replacements after they are generated. Can be used when modules require special formatting of token text, for example URL encoding or truncation to a specific length.
\Drupal\Core\Render\BubbleableMetadata$bubbleable_metadataThe bubbleable metadata. This is passed to the token replacement implementations so that they can attach their metadata.
Returns
array An associative array of replacement values, keyed by the original 'raw' tokens that were found in the source text. For example: $results['[node:title]'] = 'My new node';
See Also
hook_tokens()
hook_tokens_alter()

References BubbleableMetadata\addCacheableDependency(), and Drupal\moduleHandler().

Referenced by Token\replace().

Here is the call graph for this function:

Here is the caller graph for this function:

getInfo ( )

Returns metadata describing supported tokens.

The metadata array contains token type, name, and description data as well as an optional pointer indicating that the token chains to another set of tokens.

Returns
array An associative array of token information, grouped by token type. The array structure is identical to that of hook_token_info().
See Also
hook_token_info()

References Drupal\cache(), CacheBackendInterface\CACHE_PERMANENT, Drupal\languageManager(), Drupal\moduleHandler(), and LanguageInterface\TYPE_CONTENT.

Here is the call graph for this function:

replace (   $text,
array  $data = array(),
array  $options = array(),
BubbleableMetadata  $bubbleable_metadata = NULL 
)

Replaces all tokens in a given string with appropriate values.

Parameters
string$textAn HTML string containing replaceable tokens. The caller is responsible for calling ::escape() in case the $text was plain text.
array$data(optional) An array of keyed objects. For simple replacement scenarios 'node', 'user', and others are common keys, with an accompanying node or user object being the value. Some token types, like 'site', do not require any explicit information from $data and can be replaced even if it is empty.
array$options(optional) A keyed array of settings and flags to control the token replacement process. Supported options are:
  • langcode: A language code to be used when generating locale-sensitive tokens.
  • callback: A callback function that will be used to post-process the array of token replacements after they are generated.
  • clear: A boolean flag indicating that tokens should be removed from the final text if no replacement value can be generated.
\Drupal\Core\Render\BubbleableMetadata$bubbleable_metadata,|null(optional) An object to which static::generate() and the hooks and functions that it invokes will add their required bubbleable metadata.

To ensure that the metadata associated with the token replacements gets attached to the same render array that contains the token-replaced text, callers of this method are encouraged to pass in a BubbleableMetadata object and apply it to the corresponding render array. For example:

$bubbleable_metadata = new BubbleableMetadata();
$build['#markup'] = $token_service->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], [], $bubbleable_metadata);
$bubbleable_metadata->applyTo($build);

When the caller does not pass in a BubbleableMetadata object, this method creates a local one, and applies the collected metadata to the Renderer's currently active render context.

Returns
string The token result is the entered HTML text with tokens replaced. The caller is responsible for choosing the right escaping / sanitization. If the result is intended to be used as plain text, using PlainTextOutput::renderFromHtml() is recommended. If the result is just printed as part of a template relying on Twig autoescaping is possible, otherwise for example the result can be put into #markup, in which case it would be sanitized by Xss::filterAdmin().

References Token\generate(), and Token\scan().

Here is the call graph for this function:

resetInfo ( )

Resets metadata describing supported tokens.

scan (   $text)

Builds a list of all token-like patterns that appear in the text.

Parameters
string$textThe text to be scanned for possible tokens.
Returns
array An associative array of discovered tokens, grouped by type.

Referenced by Token\replace().

Here is the caller graph for this function:

setInfo ( array  $tokens)

Sets metadata describing supported tokens.

Parameters
array$tokensToken metadata that has an identical structure to the return value of hook_token_info().
See Also
hook_token_info()

Field Documentation

const TOKEN_INFO_CACHE_TAG = 'token_info'

The tag to cache token info with.


The documentation for this class was generated from the following file: