Lines: 100.00%
| Line | Hits | Source |
|---|---|---|
| 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 { | |
| 27 | 11 | if (str_starts_with($route, 'search.view_')) { |
| 28 | 4 | return TRUE; |
| 29 | } | |
| 30 | 11 | 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 { | |
| 37 | 4 | $keyword = SiteSearchQuery::scalar($query['keys'] ?? NULL); |
| 38 | 4 | if ($keyword === '') { |
| 39 | 3 | $keyword = $this->pathKeyword($path); |
| 40 | } | |
| 41 | 4 | if ($keyword === '') { |
| 42 | 2 | return NULL; |
| 43 | } | |
| 44 | ||
| 45 | 2 | return new SiteSearchHit( |
| 46 | 2 | $this->getPluginId(), |
| 47 | 2 | $keyword, |
| 48 | 2 | SiteSearchQuery::page($query), |
| 49 | 2 | SiteSearchQuery::canonical($query, ['keys']), |
| 50 | 2 | ); |
| 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 { | |
| 65 | 3 | $path = trim(rawurldecode($path), '/'); |
| 66 | 3 | $parts = explode('/', $path); |
| 67 | 3 | if (count($parts) < 3 || $parts[0] !== 'search') { |
| 68 | 2 | return ''; |
| 69 | } | |
| 70 | 1 | return trim(implode('/', array_slice($parts, 2))); |
| 71 | } | |
| 72 | ||
| 73 | } |