Coverage index

src/Hook/CounterHooks.php

Lines: 100.00%

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\Entity\EntityInterface;
9
use Drupal\Core\Hook\Attribute\Hook;
10
use Drupal\Core\Session\AccountInterface;
11
use Drupal\Core\StringTranslation\TranslationInterface;
12
use Drupal\node\NodeInterface;
13
use Drupal\visitors\VisitorsCounterInterface;
14
15
/**
16
 * Implements counter hooks for nodes and entities.
17
 */
18
class CounterHooks {
19
20
  /**
21
   * Constructs a CounterHooks object.
22
   *
23
   * @param \Drupal\Core\Session\AccountInterface $currentUser
24
   *   The current user.
25
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
26
   *   The config factory.
27
   * @param \Drupal\visitors\VisitorsCounterInterface $counter
28
   *   The visitors counter.
29
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation
30
   *   The string translation service.
31
   */
32
  public function __construct(
33
    protected AccountInterface $currentUser,
34
    protected ConfigFactoryInterface $configFactory,
35
    protected VisitorsCounterInterface $counter,
36
    protected TranslationInterface $translation,
375
  ) {}
38
39
  /**
40
   * Implements hook_node_links_alter().
41
   */
42
  #[Hook('node_links_alter')]
43
  public function nodeLinksAlter(array &$links, NodeInterface $entity, array &$context) {
443
    if ($context['view_mode'] == 'rss') {
451
      return NULL;
46
    }
472
    $links['#cache']['contexts'][] = 'user.permissions';
482
    if (!$this->currentUser->hasPermission('view visitors counter')) {
491
      return NULL;
50
    }
511
    $settings = $this->configFactory->get('visitors.settings');
521
    $entity_id = (int) $entity->id();
531
    $statistics = $this->counter->fetchView('node', $entity_id);
541
    if ($statistics) {
551
      $statistics_links['visitors_counter']['title'] = $this->translation
561
        ->formatPlural($statistics->getTotalCount(), '1 view', '@count views');
571
      $links['visitors'] = [
581
        '#theme' => 'links__node__visitors',
591
        '#links' => $statistics_links,
601
        '#attributes' => [
611
          'class' => [
621
            'links',
631
            'inline',
641
          ],
651
        ],
661
      ];
67
    }
681
    $links['#cache']['max-age'] = $settings->get('counter.display_max_age');
69
  }
70
71
  /**
72
   * Implements hook_entity_delete().
73
   */
74
  #[Hook('entity_delete')]
75
  public function entityDelete(EntityInterface $entity) {
762
    $entity_id = $entity->id();
772
    if (!is_numeric($entity_id)) {
781
      return;
79
    }
801
    $entity_type = $entity->getEntityTypeId();
811
    $this->counter->deleteViews($entity_type, (int) $entity_id);
82
  }
83
84
}