You are here

public function Token::generate in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Utility/Token.php \Drupal\Core\Utility\Token::generate()

Generates replacement values for a list of tokens.

Parameters

string $type: The type of token being replaced. 'node', 'user', and 'date' are common.

array $tokens: An array of tokens to be replaced, keyed by the literal text of the token as it appeared in the source text.

array $data: 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: 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. 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_metadata: The bubbleable metadata. This is passed to the token replacement implementations so that they can attach their metadata.

Return value

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()

1 call to Token::generate()
Token::replace in core/lib/Drupal/Core/Utility/Token.php
Replaces all tokens in a given string with appropriate values.

File

core/lib/Drupal/Core/Utility/Token.php, line 297

Class

Token
Drupal placeholder/token replacement system.

Namespace

Drupal\Core\Utility

Code

public function generate($type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  foreach ($data as $object) {
    if ($object instanceof CacheableDependencyInterface || $object instanceof AttachmentsInterface) {
      $bubbleable_metadata
        ->addCacheableDependency($object);
    }
  }
  $replacements = $this->moduleHandler
    ->invokeAll('tokens', [
    $type,
    $tokens,
    $data,
    $options,
    $bubbleable_metadata,
  ]);

  // Allow other modules to alter the replacements.
  $context = [
    'type' => $type,
    'tokens' => $tokens,
    'data' => $data,
    'options' => $options,
  ];
  $this->moduleHandler
    ->alter('tokens', $replacements, $context, $bubbleable_metadata);
  return $replacements;
}