Passed
Pull Request — master (#99)
by Def
02:07
created

Email   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 145
Duplicated Lines 0 %

Test Coverage

Coverage 90.57%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 60
c 3
b 0
f 0
dl 0
loc 145
ccs 48
cts 53
cp 0.9057
rs 10
wmc 24

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getOptions() 0 9 1
A patternIdnEmail() 0 5 1
A checkDNS() 0 5 1
A allowName() 0 5 1
A enableIDN() 0 9 3
A idnToAscii() 0 3 1
C validateValue() 0 54 16
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 37
        $matches = [];
64
65 37
        if (!is_string($value)) {
66 1
            $valid = false;
67 37
        } elseif (!preg_match(
68 37
            '/^(?P<name>(?:"?([^"]*)"?\s)?)(?:\s+)?(?:(?P<open><?)((?P<local>.+)@(?P<domain>[^>]+))(?P<close>>?))$/i',
69
            $value,
70
            $matches
71
        )) {
72 2
            $valid = false;
73
        } else {
74
            /** @psalm-var array{name:string,local:string,open:string,domain:string,close:string} $matches */
75 37
            if ($this->enableIDN) {
76 35
                $matches['local'] = $this->idnToAscii($matches['local']);
77 35
                $matches['domain'] = $this->idnToAscii($matches['domain']);
78 35
                $value = $matches['name'] . $matches['open'] . $matches['local'] . '@' . $matches['domain'] . $matches['close'];
79
            }
80
81 37
            if (is_string($matches['local']) && strlen($matches['local']) > 64) {
82
                // The maximum total length of a user name or other local-part is 64 octets. RFC 5322 section 4.5.3.1.1
83
                // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1
84 1
                $valid = false;
85 37
            } elseif (is_string($matches['local']) && strlen($matches['local'] . '@' . $matches['domain']) > 254) {
86
                // There is a restriction in RFC 2821 on the length of an address in MAIL and RCPT commands
87
                // of 254 characters. Since addresses that do not fit in those fields are not normally useful, the
88
                // upper limit on address lengths should normally be considered to be 254.
89
                //
90
                // Dominic Sayers, RFC 3696 erratum 1690
91
                // http://www.rfc-editor.org/errata_search.php?eid=1690
92 1
                $valid = false;
93
            } else {
94 37
                $valid = preg_match($this->pattern, $value) || ($this->allowName && preg_match(
95 37
                    $this->fullPattern,
96
                    $value
97
                ));
98 37
                if ($valid && $this->checkDNS) {
99 1
                    $valid = checkdnsrr($matches['domain'] . '.', 'MX') || checkdnsrr($matches['domain'] . '.', 'A');
100
                }
101
            }
102
        }
103
104 37
        if ($this->enableIDN && $valid === false) {
105 35
            $valid = (bool) preg_match($this->patternIdnEmail, $originalValue);
106
        }
107
108 37
        if ($valid === false) {
109 37
            $result->addError(new ErrorMessage($this->message));
110
        }
111
112 37
        return $result;
113
    }
114
115 35
    private function idnToAscii($idn)
116
    {
117 35
        return idn_to_ascii($idn, 0, INTL_IDNA_VARIANT_UTS46);
118
    }
119
120
    public function patternIdnEmail(string $patternIdnEmail): self
121
    {
122
        $new = clone $this;
123
        $new->patternIdnEmail = $patternIdnEmail;
124
        return $new;
125
    }
126
127 3
    public function allowName(bool $allowName): self
128
    {
129 3
        $new = clone $this;
130 3
        $new->allowName = $allowName;
131 3
        return $new;
132
    }
133
134 1
    public function checkDNS(bool $checkDNS): self
135
    {
136 1
        $new = clone $this;
137 1
        $new->checkDNS = $checkDNS;
138 1
        return $new;
139
    }
140
141 35
    public function enableIDN(bool $enableIDN): self
142
    {
143 35
        if ($enableIDN && !function_exists('idn_to_ascii')) {
144
            throw new \RuntimeException('In order to use IDN validation intl extension must be installed and enabled.');
145
        }
146
147 35
        $new = clone $this;
148 35
        $new->enableIDN = $enableIDN;
149 35
        return $new;
150
    }
151
152 4
    public function getOptions(): array
153
    {
154 4
        return array_merge(
155 4
            parent::getOptions(),
156
            [
157 4
                'allowName' => $this->allowName,
158 4
                'checkDNS' => $this->checkDNS,
159 4
                'enableIDN' => $this->enableIDN,
160 4
                'message' => new ErrorMessage($this->message),
161
            ],
162
        );
163
    }
164
}
165