Completed
Push — master ( 72b4e6...7a82f7 )
by Alexander
201:42 queued 198:41
created

EmailValidator::validateValue()   B

Complexity

Conditions 11
Paths 36

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 11

Importance

Changes 0
Metric Value
cc 11
eloc 18
nc 36
nop 1
dl 0
loc 34
ccs 17
cts 17
cp 1
crap 11
rs 7.3166
c 0
b 0
f 0

How to fix   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
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\validators;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\helpers\Json;
13
use yii\web\JsExpression;
14
15
/**
16
 * EmailValidator validates that the attribute value is a valid email address.
17
 *
18
 * @author Qiang Xue <[email protected]>
19
 * @since 2.0
20
 */
21
class EmailValidator extends Validator
22
{
23
    /**
24
     * @var string the regular expression used to validate the attribute value.
25
     * @see http://www.regular-expressions.info/email.html
26
     */
27
    public $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])?$/';
28
    /**
29
     * @var string the regular expression used to validate email addresses with the name part.
30
     * This property is used only when [[allowName]] is true.
31
     * @see allowName
32
     */
33
    public $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 bool whether to allow name in the email address (e.g. "John Smith <[email protected]>"). Defaults to false.
36
     * @see fullPattern
37
     */
38
    public $allowName = false;
39
    /**
40
     * @var bool whether to check whether the email's domain exists and has either an A or MX record.
41
     * Be aware that this check can fail due to temporary DNS problems even if the email address is
42
     * valid and an email would be deliverable. Defaults to false.
43
     */
44
    public $checkDNS = false;
45
    /**
46
     * @var bool whether validation process should take into account IDN (internationalized domain
47
     * names). Defaults to false meaning that validation of emails containing IDN will always fail.
48
     * Note that in order to use IDN validation you have to install and enable `intl` PHP extension,
49
     * otherwise an exception would be thrown.
50
     */
51
    public $enableIDN = false;
52
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 42
    public function init()
58
    {
59 42
        parent::init();
60 42
        if ($this->enableIDN && !function_exists('idn_to_ascii')) {
61
            throw new InvalidConfigException('In order to use IDN validation intl extension must be installed and enabled.');
62
        }
63 42
        if ($this->message === null) {
64 42
            $this->message = Yii::t('yii', '{attribute} is not a valid email address.');
65
        }
66 42
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71 41
    protected function validateValue($value)
72
    {
73 41
        if (!is_string($value)) {
74 1
            $valid = false;
75 41
        } elseif (!preg_match('/^(?P<name>(?:"?([^"]*)"?\s)?)(?:\s+)?(?:(?P<open><?)((?P<local>.+)@(?P<domain>[^>]+))(?P<close>>?))$/i', $value, $matches)) {
76 4
            $valid = false;
77
        } else {
78 39
            if ($this->enableIDN) {
79 18
                $matches['local'] = $this->idnToAscii($matches['local']);
80 18
                $matches['domain'] = $this->idnToAscii($matches['domain']);
81 18
                $value = $matches['name'] . $matches['open'] . $matches['local'] . '@' . $matches['domain'] . $matches['close'];
82
            }
83
84 39
            if (strlen($matches['local']) > 64) {
85
                // The maximum total length of a user name or other local-part is 64 octets. RFC 5322 section 4.5.3.1.1
86
                // http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1
87 1
                $valid = false;
88 39
            } elseif (strlen($matches['local'] . '@' . $matches['domain']) > 254) {
89
                // There is a restriction in RFC 2821 on the length of an address in MAIL and RCPT commands
90
                // of 254 characters. Since addresses that do not fit in those fields are not normally useful, the
91
                // upper limit on address lengths should normally be considered to be 254.
92
                //
93
                // Dominic Sayers, RFC 3696 erratum 1690
94
                // http://www.rfc-editor.org/errata_search.php?eid=1690
95 1
                $valid = false;
96
            } else {
97 39
                $valid = preg_match($this->pattern, $value) || ($this->allowName && preg_match($this->fullPattern, $value));
98 39
                if ($valid && $this->checkDNS) {
99 1
                    $valid = $this->isDNSValid($matches['domain']);
100
                }
101
            }
102
        }
103
104 41
        return $valid ? null : [$this->message, []];
105
    }
106
107
    /**
108
     * @param string $domain
109
     * @return bool if DNS records for domain are valid
110
     * @see https://github.com/yiisoft/yii2/issues/17083
111
     */
112 1
    protected function isDNSValid($domain)
113
    {
114 1
        if (checkdnsrr($domain . '.', 'MX')) {
115 1
            $mxRecords = dns_get_record($domain . '.', DNS_MX);
116 1
            if ($mxRecords !== false && count($mxRecords) > 0) {
117 1
                return true;
118
            }
119
        }
120
121 1
        if (checkdnsrr($domain . '.', 'A')) {
122
            $aRecords = dns_get_record($domain . '.', DNS_A);
123
            if ($aRecords !== false && count($aRecords) > 0) {
124
                return true;
125
            }
126
        }
127
128 1
        return false;
129
    }
130
131 18
    private function idnToAscii($idn)
132
    {
133 18
        if (PHP_VERSION_ID < 50600) {
134
            // TODO: drop old PHP versions support
135
            return idn_to_ascii($idn);
136
        }
137
138 18
        return idn_to_ascii($idn, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
139
    }
140
141
    /**
142
     * {@inheritdoc}
143
     */
144
    public function clientValidateAttribute($model, $attribute, $view)
145
    {
146
        ValidationAsset::register($view);
147
        if ($this->enableIDN) {
148
            PunycodeAsset::register($view);
149
        }
150
        $options = $this->getClientOptions($model, $attribute);
151
152
        return 'yii.validation.email(value, messages, ' . Json::htmlEncode($options) . ');';
153
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158
    public function getClientOptions($model, $attribute)
159
    {
160
        $options = [
161
            'pattern' => new JsExpression($this->pattern),
162
            'fullPattern' => new JsExpression($this->fullPattern),
163
            'allowName' => $this->allowName,
164
            'message' => $this->formatMessage($this->message, [
165
                'attribute' => $model->getAttributeLabel($attribute),
166
            ]),
167
            'enableIDN' => (bool) $this->enableIDN,
168
        ];
169
        if ($this->skipOnEmpty) {
170
            $options['skipOnEmpty'] = 1;
171
        }
172
173
        return $options;
174
    }
175
}
176