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

RangeValidator::getClientOptions()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 18
cp 0
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 15
nc 8
nop 2
crap 20
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\helpers\ArrayHelper;
13
14
/**
15
 * RangeValidator validates that the attribute value is among a list of values.
16
 *
17
 * The range can be specified via the [[range]] property.
18
 * If the [[not]] property is set true, the validator will ensure the attribute value
19
 * is NOT among the specified range.
20
 *
21
 * @author Qiang Xue <[email protected]>
22
 * @since 2.0
23
 */
24
class RangeValidator extends Validator
25
{
26
    /**
27
     * @var array|\Traversable|\Closure a list of valid values that the attribute value should be among or an anonymous function that returns
28
     * such a list. The signature of the anonymous function should be as follows,
29
     *
30
     * ```php
31
     * function($model, $attribute) {
32
     *     // compute range
33
     *     return $range;
34
     * }
35
     * ```
36
     */
37
    public $range;
38
    /**
39
     * @var bool whether the comparison is strict (both type and value must be the same)
40
     */
41
    public $strict = false;
42
    /**
43
     * @var bool whether to invert the validation logic. Defaults to false. If set to true,
44
     * the attribute value should NOT be among the list of values defined via [[range]].
45
     */
46
    public $not = false;
47
    /**
48
     * @var bool whether to allow array type attribute.
49
     */
50
    public $allowArray = false;
51
52
53
    /**
54
     * @inheritdoc
55
     */
56 10
    public function init()
57
    {
58 10
        parent::init();
59 10
        if (!is_array($this->range)
60 10
            && !($this->range instanceof \Closure)
61 10
            && !($this->range instanceof \Traversable)
62 10
        ) {
63 1
            throw new InvalidConfigException('The "range" property must be set.');
64
        }
65 9
        if ($this->message === null) {
66 9
            $this->message = Yii::t('yii', '{attribute} is invalid.');
67 9
        }
68 9
    }
69
70
    /**
71
     * @inheritdoc
72
     */
73 8
    protected function validateValue($value)
74
    {
75 8
        $in = false;
76
77 8
        if ($this->allowArray
78 8
            && ($value instanceof \Traversable || is_array($value))
79 8
            && ArrayHelper::isSubset($value, $this->range, $this->strict)
80 8
        ) {
81 3
            $in = true;
82 3
        }
83
84 8
        if (!$in && ArrayHelper::isIn($value, $this->range, $this->strict)) {
85 5
            $in = true;
86 5
        }
87
88 8
        return $this->not !== $in ? null : [$this->message, []];
89
    }
90
91
    /**
92
     * @inheritdoc
93
     */
94 1
    public function validateAttribute($model, $attribute)
95
    {
96 1
        if ($this->range instanceof \Closure) {
97
            $this->range = call_user_func($this->range, $model, $attribute);
98
        }
99 1
        parent::validateAttribute($model, $attribute);
100 1
    }
101
102
    /**
103
     * @inheritdoc
104
     */
105
    public function clientValidateAttribute($model, $attribute, $view)
106
    {
107
        if ($this->range instanceof \Closure) {
108
            $this->range = call_user_func($this->range, $model, $attribute);
109
        }
110
111
        ValidationAsset::register($view);
112
        $options = $this->getClientOptions($model, $attribute);
113
114
        return 'yii.validation.range(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';
115
    }
116
117
    /**
118
     * @inheritdoc
119
     */
120
    public function getClientOptions($model, $attribute)
121
    {
122
        $range = [];
123
        foreach ($this->range as $value) {
0 ignored issues
show
Bug introduced by
The expression $this->range of type array|object<Traversable>|object<Closure> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
124
            $range[] = (string) $value;
125
        }
126
        $options = [
127
            'range' => $range,
128
            'not' => $this->not,
129
            'message' => Yii::$app->getI18n()->format($this->message, [
130
                'attribute' => $model->getAttributeLabel($attribute),
131
            ], Yii::$app->language),
132
        ];
133
        if ($this->skipOnEmpty) {
134
            $options['skipOnEmpty'] = 1;
135
        }
136
        if ($this->allowArray) {
137
            $options['allowArray'] = 1;
138
        }
139
140
        return $options;
141
    }
142
}
143