Lines: 100.00%
| Line | Hits | Source |
|---|---|---|
| 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) { | |
| 35 | 33 | $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 | 27 | if (empty($hostname)) { |
| 49 | 2 | return NULL; |
| 50 | } | |
| 51 | ||
| 52 | 25 | $config = $this->getConfig(); |
| 53 | 25 | $normalized_hostname = strtolower(trim($hostname)); |
| 54 | ||
| 55 | 25 | foreach ($config as $item) { |
| 56 | 25 | if (isset($item['label']) && isset($item['hosts']) && is_array($item['hosts'])) { |
| 57 | 25 | foreach ($item['hosts'] as $host) { |
| 58 | 25 | if (strtolower(trim($host)) === $normalized_hostname) { |
| 59 | 23 | return $item['label']; |
| 60 | } | |
| 61 | } | |
| 62 | } | |
| 63 | } | |
| 64 | ||
| 65 | 8 | 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 | } |