statistics.tokens.inc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. /** @var \Drupal\statistics\StatisticsStorageInterface $stats_storage */
  37. $stats_storage = \Drupal::service('statistics.storage.node');
  38. foreach ($tokens as $name => $original) {
  39. if ($name == 'total-count') {
  40. $replacements[$original] = $stats_storage->fetchView($node->id())->getTotalCount();
  41. }
  42. elseif ($name == 'day-count') {
  43. $replacements[$original] = $stats_storage->fetchView($node->id())->getDayCount();
  44. }
  45. elseif ($name == 'last-view') {
  46. $replacements[$original] = \Drupal::service('date.formatter')->format($stats_storage->fetchView($node->id())->getTimestamp());
  47. }
  48. }
  49. if ($created_tokens = $token_service->findWithPrefix($tokens, 'last-view')) {
  50. $replacements += $token_service->generate('date', $created_tokens, ['date' => $stats_storage->fetchView($node->id())->getTimestamp()], $options, $bubbleable_metadata);
  51. }
  52. }
  53. return $replacements;
  54. }