Version 1
[yaffs-website] / web / core / modules / statistics / statistics.tokens.inc
1 <?php
2
3 /**
4  * @file
5  * Builds placeholder replacement tokens for node visitor statistics.
6  */
7
8 use Drupal\Core\Render\BubbleableMetadata;
9
10 /**
11  * Implements hook_token_info().
12  */
13 function statistics_token_info() {
14   $node['total-count'] = [
15     'name' => t("Number of views"),
16     'description' => t("The number of visitors who have read the node."),
17   ];
18   $node['day-count'] = [
19     'name' => t("Views today"),
20     'description' => t("The number of visitors who have read the node today."),
21   ];
22   $node['last-view'] = [
23     'name' => t("Last view"),
24     'description' => t("The date on which a visitor last read the node."),
25     'type' => 'date',
26   ];
27
28   return [
29     'tokens' => ['node' => $node],
30   ];
31 }
32
33 /**
34  * Implements hook_tokens().
35  */
36 function statistics_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
37   $token_service = \Drupal::token();
38
39   $replacements = [];
40
41   if ($type == 'node' & !empty($data['node'])) {
42     $node = $data['node'];
43
44     foreach ($tokens as $name => $original) {
45       if ($name == 'total-count') {
46         $statistics = statistics_get($node->id());
47         $replacements[$original] = $statistics['totalcount'];
48       }
49       elseif ($name == 'day-count') {
50         $statistics = statistics_get($node->id());
51         $replacements[$original] = $statistics['daycount'];
52       }
53       elseif ($name == 'last-view') {
54         $statistics = statistics_get($node->id());
55         $replacements[$original] = format_date($statistics['timestamp']);
56       }
57     }
58
59     if ($created_tokens = $token_service->findWithPrefix($tokens, 'last-view')) {
60       $statistics = statistics_get($node->id());
61       $replacements += $token_service->generate('date', $created_tokens, ['date' => $statistics['timestamp']], $options, $bubbleable_metadata);
62     }
63   }
64
65   return $replacements;
66 }