Passed
Pull Request — master (#41)
by Alexander
09:27
created

Email::allowName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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