Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
HostnameMatcherServiceBase
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
2 / 2
9
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 match
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
8
 getConfig
n/a
0 / 0
n/a
0 / 0
0
1<?php
2
3declare(strict_types=1);
4
5namespace Drupal\visitors\Service;
6
7use Drupal\Core\Config\ConfigFactoryInterface;
8
9/**
10 * Base class for hostname matching services.
11 */
12abstract 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) {
35    $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 {
48    if (empty($hostname)) {
49      return NULL;
50    }
51
52    $config = $this->getConfig();
53    $normalized_hostname = strtolower(trim($hostname));
54
55    foreach ($config as $item) {
56      if (isset($item['label']) && isset($item['hosts']) && is_array($item['hosts'])) {
57        foreach ($item['hosts'] as $host) {
58          if (strtolower(trim($host)) === $normalized_hostname) {
59            return $item['label'];
60          }
61        }
62      }
63    }
64
65    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}