Coverage index

src/Service/SpamService.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\VisitorsSpamInterface;
9
10
/**
11
 * Service for detecting spam referrers.
12
 */
13
final class SpamService implements VisitorsSpamInterface {
14
15
  /**
16
   * The spam sites.
17
   *
18
   * @var array
19
   */
20
  private array $spamSites;
21
22
  /**
23
   * Constructs a new SpamService.
24
   *
25
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
26
   *   The configuration factory.
27
   */
28
  public function __construct(ConfigFactoryInterface $config_factory) {
2911
    $this->spamSites = $config_factory->get('visitors.spam')->get('sites') ?? [];
30
  }
31
32
  /**
33
   * {@inheritdoc}
34
   */
35
  public function match(string $host): bool {
36
37
    // Check if domain matches any spam site.
3811
    foreach ($this->spamSites as $spam_site) {
3911
      if ($this->isDomainMatch($host, $spam_site)) {
406
        return TRUE;
41
      }
42
    }
43
4411
    return FALSE;
45
  }
46
47
  /**
48
   * Checks if a domain matches a spam site pattern.
49
   *
50
   * @param string $domain
51
   *   The normalized domain to check.
52
   * @param string $spam_site
53
   *   The spam site pattern to match against.
54
   *
55
   * @return bool
56
   *   TRUE if the domain matches the spam site pattern.
57
   */
58
  private function isDomainMatch(string $domain, string $spam_site): bool {
5911
    $domain = strtolower(trim($domain));
6011
    $spam_site = strtolower(trim($spam_site));
61
62
    // Exact match.
6311
    if ($domain === $spam_site || str_ends_with($domain, '.' . $spam_site)) {
646
      return TRUE;
65
    }
66
6711
    return FALSE;
68
  }
69
70
}