You are here

function time_field_tokens in Time Field For Drupal 8.x / 9.x 8

Same name and namespace in other branches
  1. 2.x time_field.tokens.inc \time_field_tokens()

Implements hook_tokens().

File

./time_field.tokens.inc, line 49
Token callbacks for the token module.

Code

function time_field_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  /** @var \Drupal\Core\Field\FieldItemList $list */
  if (isset($data['field_name'])) {
    $list = $data[$data['field_name']];
    foreach ($list as $type) {
      if ($type instanceof TimeType) {
        foreach ($tokens as $name => $original) {

          // Ignore default value.
          if ($name === 'value') {
            $time = Time::createFromTimestamp($type->value);
            $replacements[$original] = $time
              ->format('g:i a');
            continue;
          }
          $time = Time::createFromTimestamp($type->value);
          $replacements[$original] = $time
            ->format($name);
        }
      }
      if ($type instanceof TimeRangeType) {
        foreach ($tokens as $name => $original) {

          // Ignore default value.
          if ($name === 'to:value' || $name === 'from:value') {
            continue;
          }
          if ($name === 'to') {
            $time = Time::createFromTimestamp($type->to);
            $replacements[$original] = $time
              ->format('g:i a');
          }
          if ($name === 'from') {
            $time = Time::createFromTimestamp($type->from);
            $replacements[$original] = $time
              ->format('g:i a');
          }
          if (strpos($name, 'to:') === 0) {
            $time = Time::createFromTimestamp($type->to);
            $replacements[$original] = $time
              ->format(str_replace('to:', '', $name));
          }
          if (strpos($name, 'from:') === 0) {
            $time = Time::createFromTimestamp($type->from);
            $replacements[$original] = $time
              ->format(str_replace('from:', '', $name));
          }
        }
      }
    }
  }
  return $replacements;
}