Coverage index

src/Service/SearchEngineService.php

Lines: 100.00%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Service;
6
7
use Drupal\Core\Config\ConfigFactoryInterface;
8
use Drupal\visitors\VisitorsSearchEngineInterface;
9
10
/**
11
 * Service for matching URLs to search engines.
12
 */
13
final class SearchEngineService implements VisitorsSearchEngineInterface {
14
15
  /**
16
   * The config factory service.
17
   *
18
   * @var \Drupal\Core\Config\ConfigFactoryInterface
19
   */
20
  private ConfigFactoryInterface $configFactory;
21
22
  /**
23
   * Cached search engines configuration.
24
   *
25
   * @var array|null
26
   */
27
  private ?array $searchEngines = NULL;
28
29
  /**
30
   * Constructs a new SearchEngineService.
31
   *
32
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
33
   *   The config factory service.
34
   */
35
  public function __construct(ConfigFactoryInterface $config_factory) {
3628
    $this->configFactory = $config_factory;
37
  }
38
39
  /**
40
   * {@inheritdoc}
41
   */
42
  public function match(string $url): ?array {
4315
    $parsed_url = parse_url($url);
44
4515
    if (!$parsed_url || !isset($parsed_url['host'])) {
461
      return NULL;
47
    }
48
4915
    $search_engines = $this->getSearchEngines();
5015
    $host = strtolower($parsed_url['host']);
5115
    $query_string = $parsed_url['query'] ?? '';
5215
    $path = $parsed_url['path'] ?? '';
53
5415
    foreach ($search_engines as $engine) {
5515
      foreach ($engine['variants'] as $variant) {
5615
        if ($this->matchVariant($host, $query_string, $path, $variant)) {
5712
          return [
5812
            'name' => $engine['label'],
5912
            'variant' => $variant,
6012
            'keyword' => $this->extractKeyword($query_string, $path, $variant),
6112
          ];
62
        }
63
      }
64
    }
65
664
    return NULL;
67
  }
68
69
  /**
70
   * Gets the search engines configuration.
71
   *
72
   * @return array
73
   *   The search engines configuration.
74
   */
75
  private function getSearchEngines(): array {
7616
    if ($this->searchEngines === NULL) {
7716
      $config = $this->configFactory->get('visitors.search_engines');
7816
      $this->searchEngines = $config->get('sites') ?? [];
79
    }
80
8116
    return $this->searchEngines;
82
  }
83
84
  /**
85
   * Matches a URL against a search engine variant.
86
   *
87
   * @param string $host
88
   *   The hostname from the URL.
89
   * @param string $query_string
90
   *   The query string from the URL.
91
   * @param string $path
92
   *   The path from the URL.
93
   * @param array $variant
94
   *   The search engine variant configuration.
95
   *
96
   * @return bool
97
   *   TRUE if the variant matches, FALSE otherwise.
98
   */
99
  private function matchVariant(string $host, string $query_string, string $path, array $variant): bool {
10015
    $urls = $variant['urls'] ?? [];
101
10215
    foreach ($urls as $pattern) {
10315
      if ($this->matchHostPattern($host, $pattern)) {
104
        // Check for hidden keywords that should exclude this match.
10513
        if (isset($variant['hiddenkeyword'])) {
10610
          foreach ($variant['hiddenkeyword'] as $hidden_pattern) {
10710
            if ($this->matchesHiddenKeyword($query_string, $path, $hidden_pattern)) {
1082
              return FALSE;
109
            }
110
          }
111
        }
11212
        return TRUE;
113
      }
114
    }
115
11614
    return FALSE;
117
  }
118
119
  /**
120
   * Matches a hostname against a pattern.
121
   *
122
   * @param string $host
123
   *   The hostname to match.
124
   * @param string $pattern
125
   *   The pattern to match against.
126
   *
127
   * @return bool
128
   *   TRUE if the pattern matches, FALSE otherwise.
129
   */
130
  private function matchHostPattern(string $host, string $pattern): bool {
131
    // Handle wildcard patterns like 'google.{}' or '{}.google.com'.
13215
    $pattern = strtolower($pattern);
133
13415
    if (strpos($pattern, '{}') !== FALSE) {
135
      // Replace {} placeholder with a temporary marker.
13614
      $temp_marker = '__WILDCARD_PLACEHOLDER__';
13714
      $regex_pattern = str_replace('{}', $temp_marker, $pattern);
138
139
      // Escape the entire pattern for regex.
14014
      $regex_pattern = preg_quote($regex_pattern, '/');
141
142
      // Replace the temporary marker with the actual wildcard pattern.
14314
      $regex_pattern = str_replace($temp_marker, '[a-z0-9.-]+', $regex_pattern);
144
14514
      return (bool) preg_match('/^' . $regex_pattern . '$/', $host);
146
    }
147
148
    // Exact match.
14915
    return $host === $pattern;
150
  }
151
152
  /**
153
   * Checks if the URL matches a hidden keyword pattern.
154
   *
155
   * @param string $query_string
156
   *   The query string from the URL.
157
   * @param string $path
158
   *   The path from the URL.
159
   * @param string $pattern
160
   *   The hidden keyword pattern.
161
   *
162
   * @return bool
163
   *   TRUE if matches hidden keyword, FALSE otherwise.
164
   */
165
  private function matchesHiddenKeyword(string $query_string, string $path, string $pattern): bool {
166
    // Handle regex patterns.
16710
    if (preg_match('/^\/.*\/$/', $pattern)) {
16810
      $full_url_part = $path . ($query_string ? '?' . $query_string : '');
169
170
      // Special handling for Google search patterns
171
      // Don't exclude /search URLs that have a 'q' parameter (actual searches)
17210
      if ($pattern === '/\/search(\?.*)?/' && $path === '/search' && strpos($query_string, 'q=') !== FALSE) {
1736
        return FALSE;
174
      }
175
17610
      return (bool) preg_match($pattern, $full_url_part);
177
    }
178
179
    // Handle exact matches.
1809
    return $query_string === $pattern || $path === $pattern;
181
  }
182
183
  /**
184
   * Extracts the search keyword from the URL.
185
   *
186
   * @param string $query_string
187
   *   The query string from the URL.
188
   * @param string $path
189
   *   The path from the URL.
190
   * @param array $variant
191
   *   The search engine variant configuration.
192
   *
193
   * @return string|null
194
   *   The extracted keyword, or NULL if not found.
195
   */
196
  private function extractKeyword(string $query_string, string $path, array $variant): ?string {
19712
    $params = $variant['params'] ?? [];
198
19912
    foreach ($params as $param) {
200
      // Handle regex parameter patterns.
20112
      if (preg_match('/^\/.*\/$/', $param)) {
2023
        $full_url_part = $path . ($query_string ? '?' . $query_string : '');
2033
        if (preg_match($param, $full_url_part, $matches)) {
2041
          return isset($matches[1]) ? urldecode($matches[1]) : NULL;
205
        }
206
      }
207
      // Handle query parameters.
208
      else {
20911
        parse_str($query_string, $query_params);
21011
        if (isset($query_params[$param]) && !empty($query_params[$param])) {
21111
          return urldecode((string) $query_params[$param]);
212
        }
213
      }
214
    }
215
2166
    return NULL;
217
  }
218
219
}