Coverage index

src/Service/HostnameMatcherServiceBase.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
9
/**
10
 * Base class for hostname matching services.
11
 */
12
abstract class HostnameMatcherServiceBase {
13
14
  /**
15
   * The config factory service.
16
   *
17
   * @var \Drupal\Core\Config\ConfigFactoryInterface
18
   */
19
  protected ConfigFactoryInterface $configFactory;
20
21
  /**
22
   * Cached configuration data.
23
   *
24
   * @var array|null
25
   */
26
  protected ?array $cachedConfig = NULL;
27
28
  /**
29
   * Constructs a new HostnameMatcherServiceBase.
30
   *
31
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
32
   *   The config factory service.
33
   */
34
  public function __construct(ConfigFactoryInterface $config_factory) {
3533
    $this->configFactory = $config_factory;
36
  }
37
38
  /**
39
   * Match a hostname against the configured list.
40
   *
41
   * @param string $hostname
42
   *   The hostname to match.
43
   *
44
   * @return string|null
45
   *   The label if matched, null otherwise.
46
   */
47
  public function match(string $hostname): ?string {
4827
    if (empty($hostname)) {
492
      return NULL;
50
    }
51
5225
    $config = $this->getConfig();
5325
    $normalized_hostname = strtolower(trim($hostname));
54
5525
    foreach ($config as $item) {
5625
      if (isset($item['label']) && isset($item['hosts']) && is_array($item['hosts'])) {
5725
        foreach ($item['hosts'] as $host) {
5825
          if (strtolower(trim($host)) === $normalized_hostname) {
5923
            return $item['label'];
60
          }
61
        }
62
      }
63
    }
64
658
    return NULL;
66
  }
67
68
  /**
69
   * Get the configuration data.
70
   *
71
   * @return array
72
   *   The configuration data.
73
   */
74
  abstract protected function getConfig(): array;
75
76
}