Passed
Pull Request — master (#99)
by Def
01:59
created

Email::patternIdnEmail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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