statistics.tokens.inc 1.8 KB

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