Passed
Push — master ( 030526...f00e44 )
by Alexander
29:18 queued 25:22
created

NumberValidator   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 174
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 46
eloc 72
dl 0
loc 174
ccs 61
cts 61
cp 1
rs 8.72
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
C validateValue() 0 21 12
C validateAttribute() 0 23 12
B getClientOptions() 0 34 7
A clientValidateAttribute() 0 6 1
B init() 0 12 7
B isNotNumber() 0 6 7

How to fix   Complexity   

Complex Class

Complex classes like NumberValidator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use NumberValidator, and based on these observations, apply Extract Interface, too.

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\helpers\Json;
12
use yii\helpers\StringHelper;
13
use yii\web\JsExpression;
14
15
/**
16
 * NumberValidator validates that the attribute value is a number.
17
 *
18
 * The format of the number must match the regular expression specified in [[integerPattern]] or [[numberPattern]].
19
 * Optionally, you may configure the [[max]] and [[min]] properties to ensure the number
20
 * is within certain range.
21
 *
22
 * @author Qiang Xue <[email protected]>
23
 * @since 2.0
24
 */
25
class NumberValidator extends Validator
26
{
27
    /**
28
     * @var bool whether to allow array type attribute. Defaults to false.
29
     * @since 2.0.42
30
     */
31
    public $allowArray = false;
32
33
    /**
34
     * @var bool whether the attribute value can only be an integer. Defaults to false.
35
     */
36
    public $integerOnly = false;
37
    /**
38
     * @var int|float upper limit of the number. Defaults to null, meaning no upper limit.
39
     * @see tooBig for the customized message used when the number is too big.
40
     */
41
    public $max;
42
    /**
43
     * @var int|float lower limit of the number. Defaults to null, meaning no lower limit.
44
     * @see tooSmall for the customized message used when the number is too small.
45
     */
46
    public $min;
47
    /**
48
     * @var string user-defined error message used when the value is bigger than [[max]].
49
     */
50
    public $tooBig;
51
    /**
52
     * @var string user-defined error message used when the value is smaller than [[min]].
53
     */
54
    public $tooSmall;
55
    /**
56
     * @var string the regular expression for matching integers.
57
     */
58
    public $integerPattern = '/^[+-]?\d+$/';
59
    /**
60
     * @var string the regular expression for matching numbers. It defaults to a pattern
61
     * that matches floating numbers with optional exponential part (e.g. -1.23e-10).
62
     */
63 71
    public $numberPattern = '/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/';
64
65 71
66 71
    /**
67 70
     * {@inheritdoc}
68 62
     */
69
    public function init()
70 71
    {
71 43
        parent::init();
72
        if ($this->message === null) {
73 71
            $this->message = $this->integerOnly ? Yii::t('yii', '{attribute} must be an integer.')
74 43
                : Yii::t('yii', '{attribute} must be a number.');
75
        }
76 71
        if ($this->min !== null && $this->tooSmall === null) {
77
            $this->tooSmall = Yii::t('yii', '{attribute} must be no less than {min}.');
78
        }
79
        if ($this->max !== null && $this->tooBig === null) {
80
            $this->tooBig = Yii::t('yii', '{attribute} must be no greater than {max}.');
81 20
        }
82
    }
83 20
84 20
    /**
85 3
     * {@inheritdoc}
86 3
     */
87
    public function validateAttribute($model, $attribute)
88 19
    {
89
        $value = $model->$attribute;
90 19
        if (is_array($value) && !$this->allowArray) {
91 5
            $this->addError($model, $attribute, $this->message);
92
            return;
93 19
        }
94 2
        $values = !is_array($value) ? [$value] : $value;
95
        foreach ($values as $value) {
96 19
            if ($this->isNotNumber($value)) {
97 1
                $this->addError($model, $attribute, $this->message);
98
                return;
99 19
            }
100
            $pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
101
102
            if (!preg_match($pattern, StringHelper::normalizeNumber($value))) {
103
                $this->addError($model, $attribute, $this->message);
104 15
            }
105
            if ($this->min !== null && $value < $this->min) {
106 15
                $this->addError($model, $attribute, $this->tooSmall, ['min' => $this->min]);
107 3
            }
108
            if ($this->max !== null && $value > $this->max) {
109 13
                $this->addError($model, $attribute, $this->tooBig, ['max' => $this->max]);
110 13
            }
111 7
        }
112 12
    }
113 2
114 12
    /**
115 2
     * {@inheritdoc}
116
     */
117
    protected function validateValue($value)
118 12
    {
119
        if (is_array($value) && !$this->allowArray) {
120
            return [Yii::t('yii', '{attribute} is invalid.'), []];
121
        }
122
        $values = !is_array($value) ? [$value] : $value;
123
        foreach ($values as $value) {
0 ignored issues
show
introduced by
$value is overwriting one of the parameters of this function.
Loading history...
124 31
            if ($this->isNotNumber($value)) {
125
                return [Yii::t('yii', '{attribute} is invalid.'), []];
126 31
            }
127 31
            $pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
128 31
            if (!preg_match($pattern, StringHelper::normalizeNumber($value))) {
129 31
                return [$this->message, []];
130
            } elseif ($this->min !== null && $value < $this->min) {
131
                return [$this->tooSmall, ['min' => $this->min]];
132
            } elseif ($this->max !== null && $value > $this->max) {
133
                return [$this->tooBig, ['max' => $this->max]];
134
            }
135 1
        }
136
137 1
        return null;
138 1
    }
139
140 1
    /**
141
     * @param mixed $value the data value to be checked.
142
     */
143
    private function isNotNumber($value)
144
    {
145
        return is_array($value)
146 1
            || is_bool($value)
147
            || (is_object($value) && !method_exists($value, '__toString'))
148 1
            || (!is_object($value) && !is_scalar($value) && $value !== null);
149
    }
150
151 1
    /**
152 1
     * {@inheritdoc}
153 1
     */
154
    public function clientValidateAttribute($model, $attribute, $view)
155
    {
156
        ValidationAsset::register($view);
157 1
        $options = $this->getClientOptions($model, $attribute);
158
159
        return 'yii.validation.number(value, messages, ' . Json::htmlEncode($options) . ');';
160 1
    }
161 1
162 1
    /**
163 1
     * {@inheritdoc}
164
     */
165
    public function getClientOptions($model, $attribute)
166 1
    {
167
        $label = $model->getAttributeLabel($attribute);
168
169 1
        $options = [
170 1
            'pattern' => new JsExpression($this->integerOnly ? $this->integerPattern : $this->numberPattern),
171 1
            'message' => $this->formatMessage($this->message, [
172 1
                'attribute' => $label,
173
            ]),
174
        ];
175 1
176 1
        if ($this->min !== null) {
177
            // ensure numeric value to make javascript comparison equal to PHP comparison
178
            // https://github.com/yiisoft/yii2/issues/3118
179 1
            $options['min'] = is_string($this->min) ? (float) $this->min : $this->min;
0 ignored issues
show
introduced by
The condition is_string($this->min) is always false.
Loading history...
180
            $options['tooSmall'] = $this->formatMessage($this->tooSmall, [
181
                'attribute' => $label,
182
                'min' => $this->min,
183
            ]);
184
        }
185
        if ($this->max !== null) {
186
            // ensure numeric value to make javascript comparison equal to PHP comparison
187
            // https://github.com/yiisoft/yii2/issues/3118
188
            $options['max'] = is_string($this->max) ? (float) $this->max : $this->max;
0 ignored issues
show
introduced by
The condition is_string($this->max) is always false.
Loading history...
189
            $options['tooBig'] = $this->formatMessage($this->tooBig, [
190
                'attribute' => $label,
191
                'max' => $this->max,
192
            ]);
193
        }
194
        if ($this->skipOnEmpty) {
195
            $options['skipOnEmpty'] = 1;
196
        }
197
198
        return $options;
199
    }
200
}
201