Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
10 / 10 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| SpamService | |
100.00% |
10 / 10 |
|
100.00% |
3 / 3 |
7 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| match | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
| isDomainMatch | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| 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) { |
| 29 | $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. |
| 38 | foreach ($this->spamSites as $spam_site) { |
| 39 | if ($this->isDomainMatch($host, $spam_site)) { |
| 40 | return TRUE; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | 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 { |
| 59 | $domain = strtolower(trim($domain)); |
| 60 | $spam_site = strtolower(trim($spam_site)); |
| 61 | |
| 62 | // Exact match. |
| 63 | if ($domain === $spam_site || str_ends_with($domain, '.' . $spam_site)) { |
| 64 | return TRUE; |
| 65 | } |
| 66 | |
| 67 | return FALSE; |
| 68 | } |
| 69 | |
| 70 | } |