You are here

function scheduler_tokens in Scheduler 2.x

Same name and namespace in other branches
  1. 8 scheduler.tokens.inc \scheduler_tokens()
  2. 7 scheduler.tokens.inc \scheduler_tokens()

Implements hook_tokens().

File

./scheduler.tokens.inc, line 37
Builds placeholder replacement tokens for node scheduler data.

Code

function scheduler_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $token_service = \Drupal::token();
  $date_formatter = \Drupal::service('date.formatter');
  $language_code = isset($options['langcode']) ? $options['langcode'] : NULL;
  $replacements = [];
  $plugin_types = \Drupal::service('scheduler.manager')
    ->getPluginEntityTypes();
  if (in_array($type, $plugin_types) && !empty($data[$type])) {
    $entity = $data[$type];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'scheduler-publish':
          if (isset($entity->publish_on->value)) {
            $replacements[$original] = $date_formatter
              ->format($entity->publish_on->value, 'medium', '', NULL, $language_code);
          }
          break;
        case 'scheduler-unpublish':
          if (isset($entity->unpublish_on->value)) {
            $replacements[$original] = $date_formatter
              ->format($entity->unpublish_on->value, 'medium', '', NULL, $language_code);
          }
          break;
      }
    }

    // Chained token replacement.
    if (isset($entity->publish_on->value) && ($publish_tokens = $token_service
      ->findWithPrefix($tokens, 'scheduler-publish'))) {
      $replacements += $token_service
        ->generate('date', $publish_tokens, [
        'date' => $entity->publish_on->value,
      ], $options, $bubbleable_metadata);
    }
    if (isset($entity->unpublish_on->value) && ($unpublish_tokens = $token_service
      ->findWithPrefix($tokens, 'scheduler-unpublish'))) {
      $replacements += $token_service
        ->generate('date', $unpublish_tokens, [
        'date' => $entity->unpublish_on->value,
      ], $options, $bubbleable_metadata);
    }
  }
  return $replacements;
}