Test Failed
Pull Request — master (#219)
by
unknown
02:42
created

Email::checkDNS()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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