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 Andrey Kolyshkin <[email protected]> |
27
|
|
|
* @author Eduardo Gulias Davis <[email protected]> |
28
|
|
|
* @author Henrique Moody <[email protected]> |
29
|
|
|
* @author Paul Karikari <[email protected]> |
30
|
|
|
*/ |
31
|
|
|
final class Email extends AbstractRule |
32
|
|
|
{ |
33
|
|
|
/** |
34
|
|
|
* @var EmailValidator |
35
|
|
|
*/ |
36
|
|
|
private $validator; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Initializes the rule assigning the EmailValidator instance. |
40
|
|
|
* |
41
|
|
|
* If the EmailValidator instance is not defined, tries to create one. |
42
|
|
|
* |
43
|
|
|
* @param EmailValidator $validator |
44
|
|
|
*/ |
45
|
6 |
|
public function __construct(EmailValidator $validator = null) |
46
|
|
|
{ |
47
|
6 |
|
$this->validator = $validator ?: $this->createEmailValidator(); |
48
|
6 |
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* {@inheritdoc} |
52
|
|
|
*/ |
53
|
23 |
|
public function validate($input): bool |
54
|
|
|
{ |
55
|
23 |
|
if (!is_string($input)) { |
56
|
4 |
|
return false; |
57
|
|
|
} |
58
|
|
|
|
59
|
19 |
|
if (null !== $this->validator) { |
60
|
1 |
|
return $this->validator->isValid($input, new RFCValidation()); |
61
|
|
|
} |
62
|
|
|
|
63
|
18 |
|
return (bool) filter_var($input, FILTER_VALIDATE_EMAIL); |
64
|
|
|
} |
65
|
|
|
|
66
|
5 |
|
private function createEmailValidator(): ?EmailValidator |
67
|
|
|
{ |
68
|
5 |
|
if (class_exists(EmailValidator::class)) { |
69
|
5 |
|
return null; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return new EmailValidator(); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|