Coverage index

src/Hook/TokenHooks.php

Lines: 97.67%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Hook;
6
7
use Drupal\Core\Config\ConfigFactoryInterface;
8
use Drupal\Core\Datetime\DateFormatterInterface;
9
use Drupal\Core\Hook\Attribute\Hook;
10
use Drupal\Core\Render\BubbleableMetadata;
11
use Drupal\Core\StringTranslation\StringTranslationTrait;
12
use Drupal\Core\StringTranslation\TranslationInterface;
13
use Drupal\Core\Utility\Token;
14
use Drupal\visitors\VisitorsCounterInterface;
15
16
/**
17
 * Implements visitor counter token hooks.
18
 */
19
class TokenHooks {
20
  use StringTranslationTrait;
21
22
  /**
23
   * Constructs a TokenHooks object.
24
   *
25
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
26
   *   The config factory.
27
   * @param \Drupal\Core\Utility\Token $token
28
   *   The token service.
29
   * @param \Drupal\visitors\VisitorsCounterInterface $counter
30
   *   The visitors counter.
31
   * @param \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter
32
   *   The date formatter.
33
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation
34
   *   The string translation service.
35
   */
36
  public function __construct(
37
    protected ConfigFactoryInterface $configFactory,
38
    protected Token $token,
39
    protected VisitorsCounterInterface $counter,
40
    protected DateFormatterInterface $dateFormatter,
41
    TranslationInterface $translation,
42
  ) {
433
    $this->setStringTranslation($translation);
44
  }
45
46
  /**
47
   * Implements hook_token_info().
48
   */
49
  #[Hook('token_info')]
50
  public function tokenInfo() {
511
    $entity['total-count'] = [
521
      'name' => $this->t("Number of views"),
531
      'description' => $this->t("The number of visitors who have read the node."),
541
    ];
551
    $entity['day-count'] = [
561
      'name' => $this->t("Views today"),
571
      'description' => $this->t("The number of visitors who have read the node today."),
581
    ];
591
    $entity['last-view'] = [
601
      'name' => $this->t("Last view"),
611
      'description' => $this->t("The date on which a visitor last read the node."),
621
      'type' => 'date',
631
    ];
641
    $token = [
651
      'tokens' => [],
661
    ];
671
    $entity_types = $this->configFactory->get('visitors.settings')->get('counter.entity_types') ?? [];
681
    foreach ($entity_types as $entity_type) {
691
      $token['tokens'][$entity_type] = $entity;
70
    }
711
    return $token;
72
  }
73
74
  /**
75
   * Implements hook_tokens().
76
   */
77
  #[Hook('tokens')]
78
  public function tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
792
    $token_service = $this->token;
802
    $entity_types = $this->configFactory->get('visitors.settings')->get('counter.entity_types') ?? [];
812
    $replacements = [];
822
    if (!in_array($type, $entity_types) || empty($data[$type])) {
831
      return $replacements;
84
    }
851
    $entity = $data[$type];
861
    $entity_id = (int) ($entity->id() ?? 0);
871
    $entity_view = $this->counter->fetchView($type, $entity_id);
881
    foreach ($tokens as $name => $original) {
891
      if ($name == 'total-count') {
901
        $replacements[$original] = $entity_view ? $entity_view->getTotalCount() : 0;
91
      }
921
      elseif ($name == 'day-count') {
931
        $replacements[$original] = $entity_view ? $entity_view->getDayCount() : 0;
94
      }
951
      elseif ($name == 'last-view') {
961
        $replacements[$original] = $entity_view
971
          ? $this->dateFormatter->format($entity_view->getTimestamp())
980
          : $this->t('never');
99
      }
100
    }
1011
    if ($created_tokens = $token_service->findWithPrefix($tokens, 'last-view')) {
1021
      $replacements += $token_service->generate('date', $created_tokens, [
1031
        'date' => $entity_view ? $entity_view->getTimestamp() : 0,
1041
      ], $options, $bubbleable_metadata);
105
    }
1061
    return $replacements;
107
  }
108
109
}