Completed
Push — fix-numbervalidator-comma-deci... ( b17dfa )
by Alexander
23:18 queued 20:13
created

NumberValidator   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 157
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 97.3%

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 5
dl 0
loc 157
ccs 72
cts 74
cp 0.973
rs 8.6
c 0
b 0
f 0

5 Methods

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