You are here

function file_download_counter_tokens in File Download 8

Implements hook_tokens().

File

modules/file_download_counter/file_download_counter.tokens.inc, line 36
Builds placeholder replacement tokens for node visitor file_download_counter.

Code

function file_download_counter_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $token_service = \Drupal::token();
  $replacements = [];
  if ($type == 'file' & !empty($data['file'])) {
    $file = $data['file'];
    foreach ($tokens as $name => $original) {
      if ($name == 'total-count') {
        $file_download_counter = file_download_counter_get($file
          ->id());
        $replacements[$original] = $file_download_counter['totalcount'];
      }
      elseif ($name == 'day-count') {
        $file_download_counter = file_download_counter_get($file
          ->id());
        $replacements[$original] = $file_download_counter['daycount'];
      }
      elseif ($name == 'last-view') {
        $file_download_counter = file_download_counter_get($file
          ->id());
        $replacements[$original] = \Drupal::service('date.formatter')
          ->format($file_download_counter['timestamp']);
      }
    }
    if ($created_tokens = $token_service
      ->findWithPrefix($tokens, 'last-view')) {
      $file_download_counter = file_download_counter_get($file
        ->id());
      $replacements += $token_service
        ->generate('date', $created_tokens, [
        'date' => $file_download_counter['timestamp'],
      ], $options, $bubbleable_metadata);
    }
  }
  return $replacements;
}