Test Failed
Pull Request — master (#94)
by
unknown
01:55
created

Email::validateValue()   D

Complexity

Conditions 17
Paths 144

Size

Total Lines 52
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 17.0209

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 17
eloc 29
nc 144
nop 2
dl 0
loc 52
ccs 23
cts 24
cp 0.9583
crap 17.0209
rs 4.85
c 2
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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