Passed
Push — master ( 99ab46...a20a6f )
by Alexander
02:59
created

Email::rule()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\HasValidationErrorMessage;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule;
10
use Yiisoft\Validator\ValidationContext;
11
12
use function function_exists;
13
use function is_string;
14
use function strlen;
15
16
/**
17
 * EmailValidator validates that the attribute value is a valid email address.
18
 */
19
class Email extends Rule
20
{
21
    use HasValidationErrorMessage;
22
23
    /**
24
     * @var string the regular expression used to validateValue the attribute value.
25
     *
26
     * @see http://www.regular-expressions.info/email.html
27
     */
28
    private string $pattern = '/^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/';
29
    /**
30
     * @var string the regular expression used to validateValue email addresses with the name part.
31
     * This property is used only when {@see allowName()} is true.
32
     *
33
     * @see allowName
34
     */
35
    private string $fullPattern = '/^[^@]*<[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?>$/';
36
    /**
37
     * @var string the regular expression used to validate complex emails when idn is enabled.
38
     */
39
    private string $patternIdnEmail = '/^([a-zA-Z0-9._%+-]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/';
40
    /**
41
     * @var bool whether to allow name in the email address (e.g. "John Smith <[email protected]>"). Defaults to false.
42
     *
43
     * @see fullPattern
44
     */
45
    private bool $allowName = false;
46
    /**
47
     * @var bool whether to check whether the email's domain exists and has either an A or MX record.
48
     * Be aware that this check can fail due to temporary DNS problems even if the email address is
49
     * valid and an email would be deliverable. Defaults to false.
50
     */
51
    private bool $checkDNS = false;
52
    /**
53
     * @var bool whether validation process should take into account IDN (internationalized domain
54
     * names). Defaults to false meaning that validation of emails containing IDN will always fail.
55
     * Note that in order to use IDN validation you have to install and enable `intl` PHP extension,
56
     * otherwise an exception would be thrown.
57
     */
58
    private bool $enableIDN = false;
59
60
    private string $message = 'This value is not a valid email address.';
61
62 38
    public static function rule(): self
63
    {
64 38
        return new self();
65
    }
66
67 37
    protected function validateValue($value, ValidationContext $context = null): Result
68
    {
69 37
        $originalValue = $value;
70 37
        $result = new Result();
71
72 37
        if (!is_string($value)) {
73 1
            $valid = false;
74 37
        } elseif (!preg_match(
75 37
            '/^(?P<name>(?:"?([^"]*)"?\s)?)(?:\s+)?(?:(?P<open><?)((?P<local>.+)@(?P<domain>[^>]+))(?P<close>>?))$/i',
76
            $value,
77
            $matches
78
        )) {
79 2
            $valid = false;
80
        } else {
81
            /** @psalm-var array{name:string,local:string,open:string,domain:string,close:string} $matches */
82 37
            if ($this->enableIDN) {
83 35
                $matches['local'] = $this->idnToAscii($matches['local']);
84 35
                $matches['domain'] = $this->idnToAscii($matches['domain']);
85 35
                $value = $matches['name'] . $matches['open'] . $matches['local'] . '@' . $matches['domain'] . $matches['close'];
86
            }
87
88 37
            if (is_string($matches['local']) && strlen($matches['local']) > 64) {
89
                // The maximum total length of a user name or other local-part is 64 octets. RFC 5322 section 4.5.3.1.1
90
                // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1
91 1
                $valid = false;
92 37
            } elseif (is_string($matches['local']) && strlen($matches['local'] . '@' . $matches['domain']) > 254) {
93
                // There is a restriction in RFC 2821 on the length of an address in MAIL and RCPT commands
94
                // of 254 characters. Since addresses that do not fit in those fields are not normally useful, the
95
                // upper limit on address lengths should normally be considered to be 254.
96
                //
97
                // Dominic Sayers, RFC 3696 erratum 1690
98
                // http://www.rfc-editor.org/errata_search.php?eid=1690
99 1
                $valid = false;
100
            } else {
101 37
                $valid = preg_match($this->pattern, $value) || ($this->allowName && preg_match(
102 37
                    $this->fullPattern,
103
                    $value
104
                ));
105 37
                if ($valid && $this->checkDNS) {
106 1
                    $valid = checkdnsrr($matches['domain'] . '.', 'MX') || checkdnsrr($matches['domain'] . '.', 'A');
107
                }
108
            }
109
        }
110
111 37
        if ($this->enableIDN && $valid === false) {
112 35
            $valid = (bool) preg_match($this->patternIdnEmail, $originalValue);
113
        }
114
115 37
        if ($valid === false) {
116 37
            $result->addError($this->formatMessage($this->message));
117
        }
118
119 37
        return $result;
120
    }
121
122 35
    private function idnToAscii($idn)
123
    {
124 35
        return idn_to_ascii($idn, 0, INTL_IDNA_VARIANT_UTS46);
125
    }
126
127
    public function patternIdnEmail(string $patternIdnEmail): self
128
    {
129
        $new = clone $this;
130
        $new->patternIdnEmail = $patternIdnEmail;
131
        return $new;
132
    }
133
134 3
    public function allowName(bool $allowName): self
135
    {
136 3
        $new = clone $this;
137 3
        $new->allowName = $allowName;
138 3
        return $new;
139
    }
140
141 1
    public function checkDNS(bool $checkDNS): self
142
    {
143 1
        $new = clone $this;
144 1
        $new->checkDNS = $checkDNS;
145 1
        return $new;
146
    }
147
148 35
    public function enableIDN(bool $enableIDN): self
149
    {
150 35
        if ($enableIDN && !function_exists('idn_to_ascii')) {
151
            throw new \RuntimeException('In order to use IDN validation intl extension must be installed and enabled.');
152
        }
153
154 35
        $new = clone $this;
155 35
        $new->enableIDN = $enableIDN;
156 35
        return $new;
157
    }
158
159 4
    public function getOptions(): array
160
    {
161 4
        return array_merge(
162 4
            parent::getOptions(),
163
            [
164 4
                'allowName' => $this->allowName,
165 4
                'checkDNS' => $this->checkDNS,
166 4
                'enableIDN' => $this->enableIDN,
167 4
                'message' => $this->formatMessage($this->message),
168
            ],
169
        );
170
    }
171
}
172