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

Email::enableIDN()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 6
cp 0.8333
crap 3.0416
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Translator\TranslatorInterface;
8
use Yiisoft\Validator\DataSetInterface;
9
use Yiisoft\Validator\ErrorMessage;
10
use Yiisoft\Validator\HasValidationErrorMessage;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\Rule;
13
14
/**
15
 * EmailValidator validates that the attribute value is a valid email address.
16
 */
17
class Email extends Rule
18
{
19
    use HasValidationErrorMessage;
20
21
    /**
22
     * @var string the regular expression used to validateValue the attribute value.
23
     *
24
     * @see http://www.regular-expressions.info/email.html
25
     */
26
    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])?$/';
27
    /**
28
     * @var string the regular expression used to validateValue email addresses with the name part.
29
     * This property is used only when [[allowName]] is true.
30
     *
31
     * @see allowName
32
     */
33
    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])?>$/';
34
    /**
35
     * @var string the regular expression used to validate complex emails when idn is enabled.
36
     */
37
    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})(\]?)$/';
38
    /**
39
     * @var bool whether to allow name in the email address (e.g. "John Smith <[email protected]>"). Defaults to false.
40
     *
41
     * @see fullPattern
42
     */
43
    private bool $allowName = false;
44
    /**
45
     * @var bool whether to check whether the email's domain exists and has either an A or MX record.
46
     * Be aware that this check can fail due to temporary DNS problems even if the email address is
47
     * valid and an email would be deliverable. Defaults to false.
48
     */
49
    private bool $checkDNS = false;
50
    /**
51
     * @var bool whether validation process should take into account IDN (internationalized domain
52
     * names). Defaults to false meaning that validation of emails containing IDN will always fail.
53
     * Note that in order to use IDN validation you have to install and enable `intl` PHP extension,
54
     * otherwise an exception would be thrown.
55
     */
56
    private bool $enableIDN = false;
57
58
    private string $message = 'This value is not a valid email address.';
59
60 37
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
61
    {
62 37
        $originalValue = $value;
63 37
        $result = new Result();
64
        /** @var ?array $matches */
65 37
        $matches = null;
66
67 37
        if (!is_string($value)) {
68 1
            $valid = false;
69 37
        } elseif (!preg_match(
70 37
            '/^(?P<name>(?:"?([^"]*)"?\s)?)(?:\s+)?(?:(?P<open><?)((?P<local>.+)@(?P<domain>[^>]+))(?P<close>>?))$/i',
71
            $value,
72
            $matches
73
        )) {
74 2
            $valid = false;
75
        } else {
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($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(?TranslatorInterface $translator = null): 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))->withTranslator($translator),
162
            ],
163
        );
164
    }
165
}
166