Completed
Push — master ( 0261a5...cdaf5c )
by Dmitry
123:40 queued 120:32
created

NumberValidator   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 145
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 34
lcom 1
cbo 5
dl 0
loc 145
ccs 69
cts 69
cp 1
rs 9.2
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
B init() 0 14 7
B validateValue() 0 16 9
B validateAttribute() 0 18 10
A clientValidateAttribute() 0 7 1
C getClientOptions() 0 35 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 20
    public function init()
63
    {
64 20
        parent::init();
65 20
        if ($this->message === null) {
66 19
            $this->message = $this->integerOnly ? Yii::t('yii', '{attribute} must be an integer.')
67 19
                : Yii::t('yii', '{attribute} must be a number.');
68 19
        }
69 20
        if ($this->min !== null && $this->tooSmall === null) {
70 5
            $this->tooSmall = Yii::t('yii', '{attribute} must be no less than {min}.');
71 5
        }
72 20
        if ($this->max !== null && $this->tooBig === null) {
73 5
            $this->tooBig = Yii::t('yii', '{attribute} must be no greater than {max}.');
74 5
        }
75 20
    }
76
77
    /**
78
     * @inheritdoc
79
     */
80 5
    public function validateAttribute($model, $attribute)
81
    {
82 5
        $value = $model->$attribute;
83 5
        if (is_array($value) || (is_object($value) && !method_exists($value, '__toString'))) {
84 1
            $this->addError($model, $attribute, $this->message);
85 1
            return;
86
        }
87 5
        $pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
88 5
        if (!preg_match($pattern, "$value")) {
89 4
            $this->addError($model, $attribute, $this->message);
90 4
        }
91 5
        if ($this->min !== null && $value < $this->min) {
92 2
            $this->addError($model, $attribute, $this->tooSmall, ['min' => $this->min]);
93 2
        }
94 5
        if ($this->max !== null && $value > $this->max) {
95 1
            $this->addError($model, $attribute, $this->tooBig, ['max' => $this->max]);
96 1
        }
97 5
    }
98
99
    /**
100
     * @inheritdoc
101
     */
102 8
    protected function validateValue($value)
103
    {
104 8
        if (is_array($value) || is_object($value)) {
105 1
            return [Yii::t('yii', '{attribute} is invalid.'), []];
106
        }
107 7
        $pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
108 7
        if (!preg_match($pattern, "$value")) {
109 6
            return [$this->message, []];
110 6
        } elseif ($this->min !== null && $value < $this->min) {
111 2
            return [$this->tooSmall, ['min' => $this->min]];
112 6
        } elseif ($this->max !== null && $value > $this->max) {
113 2
            return [$this->tooBig, ['max' => $this->max]];
114
        } else {
115 6
            return null;
116
        }
117
    }
118
119
    /**
120
     * @inheritdoc
121
     */
122 1
    public function clientValidateAttribute($model, $attribute, $view)
123
    {
124 1
        ValidationAsset::register($view);
125 1
        $options = $this->getClientOptions($model, $attribute);
126
127 1
        return 'yii.validation.number(value, messages, ' . Json::htmlEncode($options) . ');';
128
    }
129
130
    /**
131
     * @inheritdoc
132
     */
133 1
    protected function getClientOptions($model, $attribute)
134
    {
135 1
        $label = $model->getAttributeLabel($attribute);
136
137
        $options = [
138 1
            'pattern' => new JsExpression($this->integerOnly ? $this->integerPattern : $this->numberPattern),
139 1
            'message' => Yii::$app->getI18n()->format($this->message, [
140 1
                'attribute' => $label,
141 1
            ], Yii::$app->language),
142 1
        ];
143
144 1
        if ($this->min !== null) {
145
            // ensure numeric value to make javascript comparison equal to PHP comparison
146
            // https://github.com/yiisoft/yii2/issues/3118
147 1
            $options['min'] = is_string($this->min) ? (float) $this->min : $this->min;
148 1
            $options['tooSmall'] = Yii::$app->getI18n()->format($this->tooSmall, [
149 1
                'attribute' => $label,
150 1
                'min' => $this->min,
151 1
            ], Yii::$app->language);
152 1
        }
153 1
        if ($this->max !== null) {
154
            // ensure numeric value to make javascript comparison equal to PHP comparison
155
            // https://github.com/yiisoft/yii2/issues/3118
156 1
            $options['max'] = is_string($this->max) ? (float) $this->max : $this->max;
157 1
            $options['tooBig'] = Yii::$app->getI18n()->format($this->tooBig, [
158 1
                'attribute' => $label,
159 1
                'max' => $this->max,
160 1
            ], Yii::$app->language);
161 1
        }
162 1
        if ($this->skipOnEmpty) {
163 1
            $options['skipOnEmpty'] = 1;
164 1
        }
165
166 1
        return $options;
167
    }
168
}
169