Passed
Push — master ( 9dbdd9...d5a428 )
by Alexander
04:15
created

framework/validators/NumberValidator.php (1 issue)

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