Coverage index

src/Plugin/VisitorsSiteSearch/CoreSearch.php

Lines: 100.00%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Plugin\VisitorsSiteSearch;
6
7
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
8
use Drupal\visitors\Attribute\VisitorsSiteSearch;
9
use Drupal\visitors\Helper\SiteSearchQuery;
10
use Drupal\visitors\Plugin\VisitorsSiteSearchBase;
11
use Drupal\visitors\SiteSearch\SiteSearchHit;
12
13
/**
14
 * Detects the Drupal core Search page.
15
 */
16
#[VisitorsSiteSearch(
17
  id: 'core_search',
18
  label: 'Core Search',
19
  weight: 0,
20
)]
21
final class CoreSearch extends VisitorsSiteSearchBase implements ContainerFactoryPluginInterface {
22
23
  /**
24
   * {@inheritdoc}
25
   */
26
  public function applies(string $route, string $path, array $query): bool {
2711
    if (str_starts_with($route, 'search.view_')) {
284
      return TRUE;
29
    }
3011
    return $route === '' && str_starts_with(trim($path, '/'), 'search/');
31
  }
32
33
  /**
34
   * {@inheritdoc}
35
   */
36
  public function parse(string $route, string $path, array $query): ?SiteSearchHit {
374
    $keyword = SiteSearchQuery::scalar($query['keys'] ?? NULL);
384
    if ($keyword === '') {
393
      $keyword = $this->pathKeyword($path);
40
    }
414
    if ($keyword === '') {
422
      return NULL;
43
    }
44
452
    return new SiteSearchHit(
462
      $this->getPluginId(),
472
      $keyword,
482
      SiteSearchQuery::page($query),
492
      SiteSearchQuery::canonical($query, ['keys']),
502
    );
51
  }
52
53
  /**
54
   * Keyword stored in the search path.
55
   *
56
   * Core Search uses /search/{page}/{keys}.
57
   *
58
   * @param string $path
59
   *   The Drupal path.
60
   *
61
   * @return string
62
   *   The decoded keyword, or an empty string.
63
   */
64
  private function pathKeyword(string $path): string {
653
    $path = trim(rawurldecode($path), '/');
663
    $parts = explode('/', $path);
673
    if (count($parts) < 3 || $parts[0] !== 'search') {
682
      return '';
69
    }
701
    return trim(implode('/', array_slice($parts, 2)));
71
  }
72
73
}