1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Respect/Validation. |
5
|
|
|
* |
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Respect\Validation\Rules; |
15
|
|
|
|
16
|
|
|
use Egulias\EmailValidator\EmailValidator; |
17
|
|
|
use Egulias\EmailValidator\Validation\RFCValidation; |
18
|
|
|
use const FILTER_VALIDATE_EMAIL; |
19
|
|
|
use function class_exists; |
20
|
|
|
use function filter_var; |
21
|
|
|
use function is_string; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Validates an email address. |
25
|
|
|
* |
26
|
|
|
* @author Eduardo Gulias Davis <[email protected]> |
27
|
|
|
* @author Henrique Moody <[email protected]> |
28
|
|
|
* @author Paul Karikari <[email protected]> |
29
|
|
|
*/ |
30
|
|
|
final class Email extends AbstractRule |
31
|
|
|
{ |
32
|
|
|
/** |
33
|
|
|
* @var EmailValidator |
34
|
|
|
*/ |
35
|
|
|
private $validator; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Initializes the rule assigning the EmailValidator instance. |
39
|
|
|
* |
40
|
|
|
* If the EmailValidator instance of not defined, tries to create one. |
41
|
|
|
* |
42
|
|
|
* @param EmailValidator $validator |
43
|
|
|
*/ |
44
|
6 |
|
public function __construct(EmailValidator $validator = null) |
45
|
|
|
{ |
46
|
6 |
|
$this->validator = $validator ?: $this->createEmailValidator(); |
47
|
6 |
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* {@inheritdoc} |
51
|
|
|
*/ |
52
|
19 |
|
public function validate($input): bool |
53
|
|
|
{ |
54
|
19 |
|
if (!is_string($input)) { |
55
|
|
|
return false; |
56
|
|
|
} |
57
|
|
|
|
58
|
19 |
|
if (null !== $this->validator) { |
59
|
1 |
|
return $this->validator->isValid($input, new RFCValidation()); |
60
|
|
|
} |
61
|
|
|
|
62
|
18 |
|
return (bool) filter_var($input, FILTER_VALIDATE_EMAIL); |
63
|
|
|
} |
64
|
|
|
|
65
|
5 |
|
private function createEmailValidator(): ?EmailValidator |
66
|
|
|
{ |
67
|
5 |
|
if (class_exists(EmailValidator::class)) { |
68
|
5 |
|
return null; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return new EmailValidator(); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|