You are here

function hook_tokens in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Utility/token.api.php \hook_tokens()

Provide replacement values for placeholder tokens.

This hook is invoked when someone calls \Drupal\Core\Utility\Token::replace(). That function first scans the text for [type:token] patterns, and splits the needed tokens into groups by type. Then hook_tokens() is invoked on each token-type group, allowing your module to respond by providing replacement text for any of the tokens in the group that your module knows how to process.

A module implementing this hook should also implement hook_token_info() in order to list its available tokens on editing screens.

Parameters

$type: The machine-readable name of the type (group) of token being replaced, such as 'node', 'user', or another type defined by a hook_token_info() implementation.

$tokens: An array of tokens to be replaced. The keys are the machine-readable token names, and the values are the raw [type:token] strings that appeared in the original text.

array $data: An associative array of data objects to be used when generating replacement values, as supplied in the $data parameter to \Drupal\Core\Utility\Token::replace().

array $options: An associative array of options for token replacement; see \Drupal\Core\Utility\Token::replace() for possible values.

\Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata: The bubbleable metadata. Prior to invoking this hook, \Drupal\Core\Utility\Token::generate() collects metadata for all of the data objects in $data. For any data sources not in $data, but that are used by the token replacement logic, such as global configuration (e.g., 'system.site') and related objects (e.g., $node->getOwner()), implementations of this hook must add the corresponding metadata. For example:

$bubbleable_metadata
  ->addCacheableDependency(\Drupal::config('system.site'));
$bubbleable_metadata
  ->addCacheableDependency($node
  ->getOwner());

Additionally, implementations of this hook, must forward $bubbleable_metadata to the chained tokens that they invoke. For example:

if ($created_tokens = $token_service
  ->findWithPrefix($tokens, 'created')) {
  $replacements = $token_service
    ->generate('date', $created_tokens, array(
    'date' => $node
      ->getCreatedTime(),
  ), $options, $bubbleable_metadata);
}

Return value

array An associative array of replacement values, keyed by the raw [type:token] strings from the original text. The returned values must be either plain text strings, or an object implementing MarkupInterface if they are HTML-formatted.

See also

hook_token_info()

hook_tokens_alter()

Related topics

17 functions implement hook_tokens()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

ArgumentsWildcardSpec::it_exposes_list_of_tokens in vendor/phpspec/prophecy/spec/Prophecy/Argument/ArgumentsWildcardSpec.php
ArgumentsWildcardSpec::it_returns_false_if_there_is_less_arguments_than_tokens in vendor/phpspec/prophecy/spec/Prophecy/Argument/ArgumentsWildcardSpec.php
ArrayEntryTokenSpec::it_scores_array_accessible_object_half_of_combined_scores_from_key_and_value_tokens in vendor/phpspec/prophecy/spec/Prophecy/Argument/Token/ArrayEntryTokenSpec.php
ArrayEntryTokenSpec::it_scores_array_half_of_combined_scores_from_key_and_value_tokens in vendor/phpspec/prophecy/spec/Prophecy/Argument/Token/ArrayEntryTokenSpec.php
ArrayEntryTokenSpec::it_scores_traversable_object_half_of_combined_scores_from_key_and_value_tokens in vendor/phpspec/prophecy/spec/Prophecy/Argument/Token/ArrayEntryTokenSpec.php

... See full list

1 invocation of hook_tokens()
Token::generate in core/lib/Drupal/Core/Utility/Token.php
Generates replacement values for a list of tokens.

File

core/lib/Drupal/Core/Utility/token.api.php, line 74
Hooks related to the Token system.

Code

function hook_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $token_service = \Drupal::token();
  $url_options = array(
    'absolute' => TRUE,
  );
  if (isset($options['langcode'])) {
    $url_options['language'] = \Drupal::languageManager()
      ->getLanguage($options['langcode']);
    $langcode = $options['langcode'];
  }
  else {
    $langcode = NULL;
  }
  $replacements = array();
  if ($type == 'node' && !empty($data['node'])) {

    /** @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
      switch ($name) {

        // Simple key values on the node.
        case 'nid':
          $replacements[$original] = $node->nid;
          break;
        case 'title':
          $replacements[$original] = $node
            ->getTitle();
          break;
        case 'edit-url':
          $replacements[$original] = $node
            ->url('edit-form', $url_options);
          break;

        // Default values for the chained tokens handled below.
        case 'author':
          $account = $node
            ->getOwner() ? $node
            ->getOwner() : User::load(0);
          $replacements[$original] = $account
            ->label();
          $bubbleable_metadata
            ->addCacheableDependency($account);
          break;
        case 'created':
          $replacements[$original] = format_date($node
            ->getCreatedTime(), 'medium', '', NULL, $langcode);
          break;
      }
    }
    if ($author_tokens = $token_service
      ->findWithPrefix($tokens, 'author')) {
      $replacements = $token_service
        ->generate('user', $author_tokens, array(
        'user' => $node
          ->getOwner(),
      ), $options, $bubbleable_metadata);
    }
    if ($created_tokens = $token_service
      ->findWithPrefix($tokens, 'created')) {
      $replacements = $token_service
        ->generate('date', $created_tokens, array(
        'date' => $node
          ->getCreatedTime(),
      ), $options, $bubbleable_metadata);
    }
  }
  return $replacements;
}