Coverage index

src/Hook/SearchHooks.php

Lines: 0.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\Hook\Attribute\Hook;
9
use Drupal\Core\Pager\PagerManagerInterface;
10
use Drupal\Core\State\StateInterface;
11
use Drupal\Core\StringTranslation\StringTranslationTrait;
12
use Drupal\Core\StringTranslation\TranslationInterface;
13
use Drupal\views\ViewExecutable;
14
use Drupal\visitors\VisitorsSiteSearchDetectorInterface;
15
use Symfony\Component\HttpFoundation\RequestStack;
16
17
/**
18
 * Implements search ranking hooks.
19
 */
20
class SearchHooks {
21
  use StringTranslationTrait;
22
23
  /**
24
   * Constructs a SearchHooks object.
25
   *
26
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
27
   *   The config factory.
28
   * @param \Drupal\Core\State\StateInterface $state
29
   *   The state service.
30
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translation
31
   *   The string translation service.
32
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
33
   *   The request stack.
34
   * @param \Drupal\Core\Pager\PagerManagerInterface $pagerManager
35
   *   The pager manager.
36
   * @param \Drupal\visitors\VisitorsSiteSearchDetectorInterface $siteSearch
37
   *   The site search detector.
38
   */
39
  public function __construct(
40
    protected ConfigFactoryInterface $configFactory,
41
    protected StateInterface $state,
42
    TranslationInterface $translation,
43
    protected RequestStack $requestStack,
44
    protected PagerManagerInterface $pagerManager,
45
    protected VisitorsSiteSearchDetectorInterface $siteSearch,
46
  ) {
470
    $this->setStringTranslation($translation);
48
  }
49
50
  /**
51
   * Implements hook_ranking() and hook_node_search_ranking().
52
   *
53
   * Hook_ranking() is used by the base search module (pre-Drupal 11.4).
54
   * hook_node_search_ranking() is used by the search_node submodule
55
   * introduced in Drupal 11.4.
56
   */
57
  #[Hook('ranking')]
58
  #[Hook('node_search_ranking')]
59
  public function ranking() {
600
    $settings = $this->configFactory->get('visitors.settings');
610
    $is_enabled_and_has_node_entity_type = $settings->get('counter.enabled') && in_array('node', $settings->get('counter.entity_types'));
620
    if ($is_enabled_and_has_node_entity_type) {
630
      return [
640
        'views' => [
650
          'title' => $this->t('Number of views'),
660
          'join' => [
670
            'type' => 'LEFT',
680
            'table' => 'visitors_counter',
690
            'alias' => 'visitors_counter',
700
            'on' => "visitors_counter.entity_id = i.sid AND visitors_counter.entity_type = 'node'",
710
          ],
72
          // Inverse law that maps the highest view count on the site to 1
73
          // and 0 to 0. Note that the ROUND here is necessary for PostgreSQL
74
          // and SQLite in order to ensure that the :statistics_scale argument
75
          // is treated as a numeric type, because the PostgreSQL PDO driver
76
          // sometimes puts values in as strings instead of numbers in complex
77
          // expressions like this.
780
          'score' => '2.0 - 2.0 / (1.0 + visitors_counter.total * (ROUND(:statistics_scale, 4)))',
790
          'arguments' => [
800
            ':statistics_scale' => $this->state->get('visitors.node_counter_scale', 0),
810
          ],
820
        ],
830
      ];
84
    }
85
  }
86
87
  /**
88
   * Implements hook_preprocess_search_results().
89
   */
90
  #[Hook('preprocess_search_results')]
91
  public function preprocessSearchResults(array &$variables): void {
920
    $this->storeSearchCount();
93
  }
94
95
  /**
96
   * Implements hook_preprocess_item_list__search_results().
97
   *
98
   * Drupal 11.4 renders search hits as an item list. The list length is the
99
   * result count when the search did not create a pager.
100
   */
101
  #[Hook('preprocess_item_list__search_results')]
102
  public function preprocessSearchResultList(array &$variables): void {
1030
    $items = $variables['items'] ?? NULL;
1040
    $shown = is_array($items) ? count($items) : NULL;
1050
    $this->storeSearchCount($shown);
106
  }
107
108
  /**
109
   * Stores the search result count for the tracking beacon.
110
   *
111
   * The pager total is used when the search created one. Otherwise the number
112
   * of results on the page is stored.
113
   *
114
   * @param int|null $shown
115
   *   The number of results rendered on this page.
116
   */
117
  protected function storeSearchCount(?int $shown = NULL): void {
1180
    $request = $this->requestStack->getCurrentRequest();
1190
    if ($request === NULL) {
1200
      return;
121
    }
1220
    $pager = $this->pagerManager->getPager();
1230
    if ($pager !== NULL) {
1240
      $request->attributes->set('visitors_search_count', $pager->getTotalItems());
1250
      return;
126
    }
1270
    if ($shown !== NULL) {
1280
      $request->attributes->set('visitors_search_count', $shown);
129
    }
130
  }
131
132
  /**
133
   * Implements hook_views_pre_render().
134
   */
135
  #[Hook('views_pre_render')]
136
  public function viewsPreRender(ViewExecutable $view): void {
1370
    if (!$this->siteSearch->tracksView($view->id(), (string) $view->current_display)) {
1380
      return;
139
    }
1400
    if (!is_numeric($view->total_rows) || (int) $view->total_rows < 0) {
1410
      return;
142
    }
1430
    $request = $this->requestStack->getCurrentRequest();
1440
    if ($request === NULL) {
1450
      return;
146
    }
1470
    $request->attributes->set('visitors_search_count', (int) $view->total_rows);
148
  }
149
150
}