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