Passed
Pull Request — master (#94)
by
unknown
01:43
created

Email::validateValue()   C

Complexity

Conditions 16
Paths 96

Size

Total Lines 53
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 16.0146

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 16
eloc 30
c 3
b 0
f 0
nc 96
nop 2
dl 0
loc 53
ccs 25
cts 26
cp 0.9615
crap 16.0146
rs 5.5666

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 37
        $result = new Result();
58
59 37
        if (!is_string($value)) {
60 1
            $valid = false;
61
        } elseif (!preg_match(
62 37
            '/^(?P<name>(?:"?([^"]*)"?\s)?)(?:\s+)?(?:(?P<open><?)((?P<local>.+)@(?P<domain>[^>]+))(?P<close>>?))$/i',
63
            $value,
64
            $matches
65
        )) {
66 2
            $valid = false;
67
        } else {
68 37
            if ($this->enableIDN) {
69 35
                $matches['local'] = $this->idnToAscii($matches['local']);
70 35
                $matches['domain'] = $this->idnToAscii($matches['domain']);
71 35
                $value = $matches['name'] . $matches['open'] . $matches['local'] . '@' . $matches['domain'] . $matches['close'];
72
            }
73
74 37
            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
                // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1
77 1
                $valid = false;
78 37
            } 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
                // http://www.rfc-editor.org/errata_search.php?eid=1690
85 1
                $valid = false;
86
            } else {
87 37
                $valid = preg_match($this->pattern, $value) || ($this->allowName && preg_match(
88 37
                    $this->fullPattern,
89
                    $value
90
                ));
91 37
                if ($valid && $this->checkDNS) {
92 1
                    $valid = checkdnsrr($matches['domain'] . '.', 'MX') || checkdnsrr($matches['domain'] . '.', 'A');
93
                }
94
            }
95
        }
96
97 37
        if ($this->enableIDN && $valid === false) {
98 35
            $pattern = '/^([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})(\]?)$/';
99 35
            $valid = (bool) preg_match($pattern, $originalValue);
100
        }
101
102 37
        if ($valid === false) {
103 37
            $result->addError($this->translateMessage($this->message));
104
        }
105
106 37
        return $result;
107
    }
108
109 35
    private function idnToAscii($idn)
110
    {
111 35
        return idn_to_ascii($idn, 0, INTL_IDNA_VARIANT_UTS46);
112
    }
113
114 3
    public function allowName(bool $allowName): self
115
    {
116 3
        $new = clone $this;
117 3
        $new->allowName = $allowName;
118 3
        return $new;
119
    }
120
121 1
    public function checkDNS(bool $checkDNS): self
122
    {
123 1
        $new = clone $this;
124 1
        $new->checkDNS = $checkDNS;
125 1
        return $new;
126
    }
127
128 35
    public function enableIDN(bool $enableIDN): self
129
    {
130 35
        if ($enableIDN && !function_exists('idn_to_ascii')) {
131
            throw new \RuntimeException('In order to use IDN validation intl extension must be installed and enabled.');
132
        }
133
134 35
        $new = clone $this;
135 35
        $new->enableIDN = $enableIDN;
136 35
        return $new;
137
    }
138
139 4
    public function getOptions(): array
140
    {
141 4
        return array_merge(
142
            parent::getOptions(),
143
            [
144 4
                'allowName' => $this->allowName,
145 4
                'checkDNS' => $this->checkDNS,
146 4
                'enableIDN' => $this->enableIDN,
147 4
                'message' => $this->translateMessage($this->message),
148
            ],
149
        );
150
    }
151
}
152