Coverage index

src/Service/SiteSearchService.php

Lines: 73.08%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Service;
6
7
use Drupal\Component\Utility\Unicode;
8
use Drupal\Core\Path\CurrentPathStack;
9
use Drupal\Core\Routing\RouteMatchInterface;
10
use Drupal\visitors\Helper\SiteSearchQuery;
11
use Drupal\visitors\SiteSearch\SiteSearchHit;
12
use Drupal\visitors\VisitorsSiteSearchDetectorInterface;
13
use Drupal\visitors\VisitorsSiteSearchInterface;
14
use Drupal\visitors\VisitorsSiteSearchPluginManager;
15
use Symfony\Component\HttpFoundation\RequestStack;
16
17
/**
18
 * Classifies a page view against the previous site search.
19
 */
20
final class SiteSearchService implements VisitorsSiteSearchDetectorInterface {
21
22
  /**
23
   * Constructs a site search service.
24
   *
25
   * @param \Drupal\visitors\VisitorsSiteSearchPluginManager $pluginManager
26
   *   The site search plugin manager.
27
   * @param \Drupal\Core\Routing\RouteMatchInterface $routeMatch
28
   *   The current route match.
29
   * @param \Drupal\Core\Path\CurrentPathStack $currentPath
30
   *   The current path.
31
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
32
   *   The request stack.
33
   */
34
  public function __construct(
35
    protected VisitorsSiteSearchPluginManager $pluginManager,
36
    protected RouteMatchInterface $routeMatch,
37
    protected CurrentPathStack $currentPath,
38
    protected RequestStack $requestStack,
3911
  ) {}
40
41
  /**
42
   * {@inheritdoc}
43
   */
44
  public function eventFields(
45
    string $route,
46
    string $path,
47
    string $url,
48
    string $referrerRoute,
49
    string $referrerPath,
50
    string $referrerUrl,
51
    array $beacon,
52
  ): ?array {
5311
    $current = $this->detect($route, $path, $url, $beacon, TRUE);
5411
    if ($current === NULL) {
557
      return NULL;
56
    }
575
    $previous = $this->detect($referrerRoute, $referrerPath, $referrerUrl, [], FALSE);
585
    $current = $this->limit($current);
595
    if ($previous !== NULL) {
603
      $previous = $this->limit($previous);
61
    }
62
635
    return [
645
      'event_category' => 'Search',
655
      'event_action' => $this->action($current, $previous),
665
      'event_name' => $current->keyword,
675
      'event_value' => $this->count($beacon),
685
      'plugin_int_1' => $current->page,
695
      'plugin_var_1' => $current->filters,
705
      'plugin_var_2' => $previous?->keyword,
715
      'plugin_int_2' => $previous?->page,
725
      'plugin' => $current->pluginId,
735
    ];
74
  }
75
76
  /**
77
   * {@inheritdoc}
78
   */
79
  public function resultCount(): ?int {
800
    $request = $this->requestStack->getCurrentRequest();
810
    $route = $this->routeMatch->getRouteName() ?? '';
820
    $path = $this->currentPath->getPath();
830
    $query = $request?->query->all() ?? [];
840
    $plugin = $this->matchingPlugin($route, $path, $query);
850
    if (!$plugin instanceof VisitorsSiteSearchInterface) {
860
      return NULL;
87
    }
880
    return $plugin->resultCount();
89
  }
90
91
  /**
92
   * {@inheritdoc}
93
   */
94
  public function tracksView(string $viewId, string $displayId): bool {
950
    if ($viewId === '' || $displayId === '') {
960
      return FALSE;
97
    }
980
    return $this->matchingPlugin('view.' . $viewId . '.' . $displayId, '', []) !== NULL;
99
  }
100
101
  /**
102
   * Detects a search on a URL.
103
   *
104
   * The first detector that applies owns the URL. An empty keyword is not a
105
   * search, and a later detector is not tried. A beacon keyword replaces the
106
   * keyword parsed from the URL.
107
   *
108
   * @param string $route
109
   *   The Drupal route name.
110
   * @param string $path
111
   *   The Drupal path.
112
   * @param string $url
113
   *   The URL, including the query string.
114
   * @param array $beacon
115
   *   The tracking query.
116
   * @param bool $useBeacon
117
   *   Whether the search beacon parameter may supply the keyword.
118
   *
119
   * @return \Drupal\visitors\SiteSearch\SiteSearchHit|null
120
   *   The search, or NULL.
121
   */
122
  private function detect(string $route, string $path, string $url, array $beacon, bool $useBeacon): ?SiteSearchHit {
12311
    if ($path === '') {
1248
      $path = SiteSearchQuery::pathFromUrl($url);
125
    }
12611
    $query = SiteSearchQuery::fromUrl($url);
12711
    $beacon_keyword = $useBeacon ? SiteSearchQuery::scalar($beacon['search'] ?? NULL) : '';
12811
    foreach ($this->plugins() as $plugin) {
12911
      if (!$plugin->applies($route, $path, $query)) {
1300
        continue;
131
      }
1326
      $parsed = $plugin->parse($route, $path, $query);
1336
      if ($beacon_keyword === '') {
1345
        return $parsed;
135
      }
1361
      return new SiteSearchHit(
1371
        $parsed?->pluginId ?? $plugin->getPluginId(),
1381
        $beacon_keyword,
1391
        $parsed?->page ?? SiteSearchQuery::page($query),
1401
        $parsed?->filters ?? SiteSearchQuery::canonical($query, [
1411
          'page',
1421
          'search',
1431
          'search_cat',
1441
          'search_count',
1451
        ]),
1461
      );
147
    }
14810
    if ($beacon_keyword === '') {
14910
      return NULL;
150
    }
1510
    return new SiteSearchHit(
1520
      'search',
1530
      $beacon_keyword,
1540
      SiteSearchQuery::page($query),
1550
      SiteSearchQuery::canonical($query, [
1560
        'page',
1570
        'search',
1580
        'search_cat',
1590
        'search_count',
1600
      ]),
1610
    );
162
  }
163
164
  /**
165
   * Classifies the current search against the referrer search.
166
   *
167
   * @param \Drupal\visitors\SiteSearch\SiteSearchHit $current
168
   *   The search on this page.
169
   * @param \Drupal\visitors\SiteSearch\SiteSearchHit|null $previous
170
   *   The search on the referrer, or NULL.
171
   *
172
   * @return string
173
   *   Search, Next, Previous, Filter, or Keyword.
174
   */
175
  private function action(SiteSearchHit $current, ?SiteSearchHit $previous): string {
1765
    if ($previous === NULL) {
1773
      return 'Search';
178
    }
1793
    $same_keyword = $current->keyword === $previous->keyword;
1803
    $same_filters = $current->filters === $previous->filters;
1813
    if ($same_keyword && $same_filters && $current->page > $previous->page) {
1821
      return 'Next';
183
    }
1843
    if ($same_keyword && $same_filters && $current->page < $previous->page) {
1852
      return 'Previous';
186
    }
1872
    if ($same_keyword && $current->page === 0 && !$same_filters) {
1882
      return 'Filter';
189
    }
1901
    if (!$same_keyword && $same_filters) {
1911
      return 'Keyword';
192
    }
1931
    return 'Search';
194
  }
195
196
  /**
197
   * Cuts the keyword and filters to the column length.
198
   *
199
   * @param \Drupal\visitors\SiteSearch\SiteSearchHit $hit
200
   *   The detected search.
201
   *
202
   * @return \Drupal\visitors\SiteSearch\SiteSearchHit
203
   *   The search that will be stored.
204
   */
205
  private function limit(SiteSearchHit $hit): SiteSearchHit {
2065
    return new SiteSearchHit(
2075
      $hit->pluginId,
2085
      Unicode::truncate($hit->keyword, 255, FALSE, FALSE),
2095
      $hit->page,
2105
      Unicode::truncate($hit->filters, 255, FALSE, FALSE),
2115
    );
212
  }
213
214
  /**
215
   * Result count sent on the tracking request.
216
   *
217
   * @param array $beacon
218
   *   The tracking query.
219
   *
220
   * @return float|null
221
   *   The count, or NULL when it was not sent.
222
   */
223
  private function count(array $beacon): ?float {
2245
    $value = $beacon['search_count'] ?? NULL;
2255
    if (!is_scalar($value)) {
2264
      return NULL;
227
    }
2282
    $value = trim((string) $value);
2292
    if ($value === '' || !is_numeric($value) || (float) $value < 0) {
2300
      return NULL;
231
    }
2322
    return (float) $value;
233
  }
234
235
  /**
236
   * First detector that owns this route.
237
   *
238
   * @param string $route
239
   *   The Drupal route name.
240
   * @param string $path
241
   *   The Drupal path.
242
   * @param array $query
243
   *   The query parameters.
244
   *
245
   * @return \Drupal\visitors\VisitorsSiteSearchInterface|null
246
   *   The detector, or NULL.
247
   */
248
  private function matchingPlugin(string $route, string $path, array $query): ?VisitorsSiteSearchInterface {
2490
    foreach ($this->plugins() as $plugin) {
2500
      if ($plugin->applies($route, $path, $query)) {
2510
        return $plugin;
252
      }
253
    }
2540
    return NULL;
255
  }
256
257
  /**
258
   * Detectors in weight order.
259
   *
260
   * @return \Drupal\visitors\VisitorsSiteSearchInterface[]
261
   *   The detectors.
262
   */
263
  private function plugins(): array {
26411
    $definitions = $this->pluginManager->getDefinitions();
26511
    uasort($definitions, static function (array $left, array $right): int {
26611
      return ($left['weight'] ?? 0) <=> ($right['weight'] ?? 0);
26711
    });
26811
    $plugins = [];
26911
    foreach (array_keys($definitions) as $id) {
27011
      $plugin = $this->pluginManager->createInstance($id);
27111
      if ($plugin instanceof VisitorsSiteSearchInterface) {
27211
        $plugins[] = $plugin;
273
      }
274
    }
27511
    return $plugins;
276
  }
277
278
}