forked from FGRibreau/mailchecker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMailChecker.php
More file actions
75 lines (60 loc) · 1.79 KB
/
MailChecker.php
File metadata and controls
75 lines (60 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
namespace Fgribreau;
class MailChecker
{
/** @var array<string, true> */
private static array $blocklist;
/**
* @internal
*/
public static function init(): void
{
self::$blocklist = require __DIR__ . '/blacklist.php';
}
/** @param array<string> $domains */
public static function addCustomDomains(array $domains): void
{
foreach ($domains as $domain) {
self::$blocklist[$domain] = true;
}
}
public static function isValid(string $email): bool
{
$email = strtolower($email);
return self::validEmail($email) && !self::isBlacklisted($email);
}
/** @return array<string> */
public static function blacklist(): array
{
return array_keys(self::$blocklist);
}
public static function isBlacklisted(string $email): bool
{
$parts = explode('@', $email);
$domain = end($parts);
return self::isDomainBlocked($domain, true);
}
public static function isDomainBlocked(string $domain, bool $checkSubdomain): bool
{
$domainSuffixes = $checkSubdomain ? self::allDomainSuffixes($domain) : [$domain];
foreach ($domainSuffixes as $domainSuffix) {
if (isset(self::$blocklist[$domainSuffix])) {
return true;
}
}
return false;
}
/** @return \Generator<string> */
private static function allDomainSuffixes(string $domain): \Generator
{
$components = explode('.', $domain);
foreach ($components as $i => $_) {
yield implode('.', array_slice($components, $i));
}
}
private static function validEmail(string $email): bool
{
return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
}
}
MailChecker::init();