statistics.tokens.inc 1.76 KB
Newer Older
1 2 3 4 5 6 7 8
<?php

/**
 * @file
 * Builds placeholder replacement tokens for node visitor statistics.
 */

/**
9
 * Implements hook_token_info().
10 11
 */
function statistics_token_info() {
12
  $node['total-count'] = array(
13 14 15
    'name' => t("Number of views"),
    'description' => t("The number of visitors who have read the node."),
  );
16
  $node['day-count'] = array(
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    'name' => t("Views today"),
    'description' => t("The number of visitors who have read the node today."),
  );
  $node['last-view'] = array(
    'name' => t("Last view"),
    'description' => t("The date on which a visitor last read the node."),
    'type' => 'date',
  );

  return array(
    'tokens' => array('node' => $node),
  );
}

/**
32
 * Implements hook_tokens().
33 34
 */
function statistics_tokens($type, $tokens, array $data = array(), array $options = array()) {
35
  $token_service = \Drupal::token();
36

37
  $replacements = array();
38 39 40 41 42

  if ($type == 'node' & !empty($data['node'])) {
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
43
      if ($name == 'total-count') {
44
        $statistics = statistics_get($node->id());
45
        $replacements[$original] = $statistics['totalcount'];
46
      }
47
      elseif ($name == 'day-count') {
48
        $statistics = statistics_get($node->id());
49
        $replacements[$original] = $statistics['daycount'];
50 51
      }
      elseif ($name == 'last-view') {
52
        $statistics = statistics_get($node->id());
53 54 55 56
        $replacements[$original] = format_date($statistics['timestamp']);
      }
    }

57
    if ($created_tokens = $token_service->findWithPrefix($tokens, 'last-view')) {
58
      $statistics = statistics_get($node->id());
59
      $replacements += $token_service->generate('date', $created_tokens, array('date' => $statistics['timestamp']), $options);
60 61 62 63 64
    }
  }

  return $replacements;
}