You are here

function smart_date_tokens in Smart Date 8

Same name and namespace in other branches
  1. 8.2 smart_date.tokens.inc \smart_date_tokens()
  2. 3.x smart_date.tokens.inc \smart_date_tokens()
  3. 3.0.x smart_date.tokens.inc \smart_date_tokens()
  4. 3.1.x smart_date.tokens.inc \smart_date_tokens()
  5. 3.2.x smart_date.tokens.inc \smart_date_tokens()
  6. 3.3.x smart_date.tokens.inc \smart_date_tokens()
  7. 3.4.x smart_date.tokens.inc \smart_date_tokens()

Implements hook_tokens().

File

./smart_date.tokens.inc, line 76

Code

function smart_date_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if (empty($data['field_property'])) {
    return $replacements;
  }
  foreach ($tokens as $token => $original) {
    $list = $data[$data['field_name']];
    if (!$list instanceof SmartDateFieldItemList) {
      continue;
    }
    $delta = 0;
    $parts = explode(':', $token, 2);

    // Test for a delta as the first part.
    if (is_numeric($parts[0])) {
      if (count($parts) > 1) {
        $delta = $parts[0];
        $parts = explode(':', $parts[1], 2);
        $property_name = $parts[0];
        $format_value = $parts[1];
      }
      else {
        continue;
      }
    }
    else {
      $property_name = $parts[0];
      $format_value = $parts[1];
    }
    if (!$format_value) {

      // Our tokens require a value, so skip if absent.
      continue;
    }

    // Now parse out the pieces of the token name.
    $name_parts = explode('-', $property_name);
    $approach = array_pop($name_parts);
    $field = $list
      ->first();
    if ($approach == 'custom') {

      // Get the requested property and apply the provided format.
      if ($name_parts && ($prop_needed = array_pop($name_parts))) {
        $field_ts = $field
          ->get($prop_needed)
          ->getValue();
        $replacements[$original] = \Drupal::service('date.formatter')
          ->format($field_ts, '', $format_value);
      }
    }
    elseif ($approach == 'format') {
      $format = \Drupal::getContainer()
        ->get('entity_type.manager')
        ->getStorage('smart_date_format')
        ->load($format_value);
      $settings = $format
        ->getOptions();

      // Apply the specified smart date format.
      // If a property was specified, only use that.
      if ($name_parts && ($prop_needed = array_pop($name_parts))) {
        $field_ts = $field
          ->get($prop_needed)
          ->getValue();
        $replacements[$original] = SmartDateTrait::formatSmartDate($field_ts, $field_ts, $settings);
      }
      else {
        $start = $field
          ->get('value')
          ->getValue();
        $end = $field
          ->get('end_value')
          ->getValue();
        $replacements[$original] = SmartDateTrait::formatSmartDate($start, $end, $settings);
      }
    }
  }
  return $replacements;
}