You are here

function publication_date_tokens in Publication Date 8.2

Same name and namespace in other branches
  1. 8 publication_date.tokens.inc \publication_date_tokens()
  2. 7.2 publication_date.tokens.inc \publication_date_tokens()
  3. 7 publication_date.tokens.inc \publication_date_tokens()

Implements hook_tokens().

File

./publication_date.tokens.inc, line 26
Builds placeholder replacement tokens for node-related data.

Code

function publication_date_tokens($type, $tokens, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata) {
  $tokenService = \Drupal::token();
  $dateFormatter = \Drupal::service('date.formatter');
  if (isset($options['langcode'])) {
    $langcode = $options['langcode'];
  }
  else {
    $langcode = LanguageInterface::LANGCODE_DEFAULT;
  }
  $replacements = [];
  if ($type == 'node' && !empty($data['node'])) {

    /** @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'published':
          $date_format = DateFormat::load('medium');
          $bubbleable_metadata
            ->addCacheableDependency($date_format);
          $replacements[$original] = $dateFormatter
            ->format($node->published_at->value, 'medium', '', NULL, $langcode);
          break;
      }
    }
    if ($published_tokens = $tokenService
      ->findWithPrefix($tokens, 'published')) {
      $replacements += $tokenService
        ->generate('date', $published_tokens, [
        'date' => $node->published_at->value,
      ], $options, $bubbleable_metadata);
    }
  }
  return $replacements;
}