Completed
Push — fix-numbervalidator-comma-deci... ( 08054b...a7f0a3 )
by Alexander
40:41 queued 37:41
created

EmailValidator::validateValue()   C

Complexity

Conditions 12
Paths 48

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 12.0155

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 5.1612
c 0
b 0
f 0
ccs 20
cts 21
cp 0.9524
cc 12
eloc 19
nc 48
nop 1
crap 12.0155

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\web\JsExpression;
13
use yii\helpers\Json;
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 8
    public function init()
58
    {
59 8
        parent::init();
60 8
        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 8
        if ($this->message === null) {
64 8
            $this->message = Yii::t('yii', '{attribute} is not a valid email address.');
65 8
        }
66 8
    }
67
68
    /**
69
     * @inheritdoc
70
     */
71 7
    protected function validateValue($value)
72
    {
73 7
        if (!is_string($value)) {
74
            $valid = false;
75 7
        } elseif (!preg_match('/^(?P<name>(?:"?([^"]*)"?\s)?)(?:\s+)?(?:(?P<open><?)((?P<local>.+)@(?P<domain>[^>]+))(?P<close>>?))$/i', $value, $matches)) {
76 4
            $valid = false;
77 4
        } else {
78 5
            if ($this->enableIDN) {
79 1
                $matches['local'] = idn_to_ascii($matches['local']);
80 1
                $matches['domain'] = idn_to_ascii($matches['domain']);
81 1
                $value = $matches['name'] . $matches['open'] . $matches['local'] . '@' . $matches['domain'] . $matches['close'];
82 1
            }
83
84 5
            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 5
            } 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 2
                $valid = false;
96 2
            } else {
97 5
                $valid = preg_match($this->pattern, $value) || $this->allowName && preg_match($this->fullPattern, $value);
98 5
                if ($valid && $this->checkDNS) {
99 1
                    $valid = checkdnsrr($matches['domain'] . '.', 'MX') || checkdnsrr($matches['domain'] . '.', 'A');
100 1
                }
101
            }
102
        }
103
104 7
        return $valid ? null : [$this->message, []];
105
    }
106
107
    /**
108
     * @inheritdoc
109
     */
110
    public function clientValidateAttribute($model, $attribute, $view)
111
    {
112
        ValidationAsset::register($view);
113
        if ($this->enableIDN) {
114
            PunycodeAsset::register($view);
115
        }
116
        $options = $this->getClientOptions($model, $attribute);
117
118
        return 'yii.validation.email(value, messages, ' . Json::htmlEncode($options) . ');';
119
    }
120
121
    /**
122
     * @inheritdoc
123
     */
124
    public function getClientOptions($model, $attribute)
125
    {
126
        $options = [
127
            'pattern' => new JsExpression($this->pattern),
128
            'fullPattern' => new JsExpression($this->fullPattern),
129
            'allowName' => $this->allowName,
130
            'message' => Yii::$app->getI18n()->format($this->message, [
131
                'attribute' => $model->getAttributeLabel($attribute),
132
            ], Yii::$app->language),
133
            'enableIDN' => (bool)$this->enableIDN,
134
        ];
135
        if ($this->skipOnEmpty) {
136
            $options['skipOnEmpty'] = 1;
137
        }
138
139
        return $options;
140
    }
141
}
142