Passed
Pull Request — master (#19663)
by Alexander
08:07
created

StringValidator   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 205
Duplicated Lines 0 %

Test Coverage

Coverage 63.64%

Importance

Changes 0
Metric Value
eloc 80
dl 0
loc 205
ccs 49
cts 77
cp 0.6364
rs 8.8798
c 0
b 0
f 0
wmc 44

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getClientOptions() 0 36 5
B validateValue() 0 23 11
B validateAttribute() 0 22 11
A clientValidateAttribute() 0 6 1
C init() 0 26 13
A isEmpty() 0 7 3

How to fix   Complexity   

Complex Class

Complex classes like StringValidator 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 StringValidator, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\validators;
9
10
use Yii;
11
use yii\helpers\Json;
12
13
/**
14
 * StringValidator validates that the attribute value is of certain length.
15
 *
16
 * Note, this validator should only be used with string-typed attributes.
17
 *
18
 * @author Qiang Xue <[email protected]>
19
 * @since 2.0
20
 */
21
class StringValidator extends Validator
22
{
23
    /**
24
     * @var int|array specifies the length limit of the value to be validated.
25
     * This can be specified in one of the following forms:
26
     *
27
     * - an integer: the exact length that the value should be of;
28
     * - an array of one element: the minimum length that the value should be of. For example, `[8]`.
29
     *   This will overwrite [[min]].
30
     * - an array of two elements: the minimum and maximum lengths that the value should be of.
31
     *   For example, `[8, 128]`. This will overwrite both [[min]] and [[max]].
32
     * @see tooShort for the customized message for a too short string.
33
     * @see tooLong for the customized message for a too long string.
34
     * @see notEqual for the customized message for a string that does not match desired length.
35
     */
36
    public $length;
37
    /**
38
     * @var int|null maximum length. If not set, it means no maximum length limit.
39
     * @see tooLong for the customized message for a too long string.
40
     */
41
    public $max;
42
    /**
43
     * @var int|null minimum length. If not set, it means no minimum length limit.
44
     * @see tooShort for the customized message for a too short string.
45
     */
46
    public $min;
47
    /**
48
     * @var string user-defined error message used when the value is not a string.
49
     */
50
    public $message;
51
    /**
52
     * @var string user-defined error message used when the length of the value is smaller than [[min]].
53
     */
54
    public $tooShort;
55
    /**
56
     * @var string user-defined error message used when the length of the value is greater than [[max]].
57
     */
58
    public $tooLong;
59
    /**
60
     * @var string user-defined error message used when the length of the value is not equal to [[length]].
61
     */
62
    public $notEqual;
63
    /**
64
     * @var string|null the encoding of the string value to be validated (e.g. 'UTF-8').
65
     * If this property is not set, [[\yii\base\Application::charset]] will be used.
66
     */
67
    public $encoding;
68
    /**
69
     * @var boolean whether to require the value to be a string data type.
70
     * If false any scalar value will be treated as it's string equivalent.
71
     * @since 2.0.33
72
     */
73
    public $strict = true;
74
75
76
    /**
77
     * {@inheritdoc}
78
     */
79 74
    public function init()
80
    {
81 74
        parent::init();
82 74
        if (is_array($this->length)) {
83 14
            if (isset($this->length[0])) {
84 14
                $this->min = $this->length[0];
85
            }
86 14
            if (isset($this->length[1])) {
87 14
                $this->max = $this->length[1];
88
            }
89 14
            $this->length = null;
90
        }
91 74
        if ($this->encoding === null) {
92 74
            $this->encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
93
        }
94 74
        if ($this->message === null) {
95 74
            $this->message = Yii::t('yii', '{attribute} must be a string.');
96
        }
97 74
        if ($this->min !== null && $this->tooShort === null) {
98 17
            $this->tooShort = Yii::t('yii', '{attribute} should contain at least {min, number} {min, plural, one{character} other{characters}}.');
99
        }
100 74
        if ($this->max !== null && $this->tooLong === null) {
101 25
            $this->tooLong = Yii::t('yii', '{attribute} should contain at most {max, number} {max, plural, one{character} other{characters}}.');
102
        }
103 74
        if ($this->length !== null && $this->notEqual === null) {
104 15
            $this->notEqual = Yii::t('yii', '{attribute} should contain {length, number} {length, plural, one{character} other{characters}}.');
105
        }
106 74
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111 18
    public function validateAttribute($model, $attribute)
112
    {
113 18
        $value = $model->$attribute;
114 18
        if (!$this->strict && is_scalar($value) && !is_string($value)) {
115
            $value = (string)$value;
116
        }
117 18
        if (!is_string($value)) {
118 2
            $this->addError($model, $attribute, $this->message);
119
120 2
            return;
121
        }
122
123 17
        $length = mb_strlen($value, $this->encoding);
124
125 17
        if ($this->min !== null && $length < $this->min) {
126 1
            $this->addError($model, $attribute, $this->tooShort, ['min' => $this->min]);
127
        }
128 17
        if ($this->max !== null && $length > $this->max) {
129 4
            $this->addError($model, $attribute, $this->tooLong, ['max' => $this->max]);
130
        }
131 17
        if ($this->length !== null && $length !== $this->length) {
132 1
            $this->addError($model, $attribute, $this->notEqual, ['length' => $this->length]);
133
        }
134 17
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139 4
    protected function validateValue($value)
140
    {
141 4
        if (!$this->strict && is_scalar($value) && !is_string($value)) {
142 1
            $value = (string)$value;
143
        }
144
145 4
        if (!is_string($value)) {
146 2
            return [$this->message, []];
147
        }
148
149 4
        $length = mb_strlen($value, $this->encoding);
150
151 4
        if ($this->min !== null && $length < $this->min) {
152 2
            return [$this->tooShort, ['min' => $this->min]];
153
        }
154 4
        if ($this->max !== null && $length > $this->max) {
155 2
            return [$this->tooLong, ['max' => $this->max]];
156
        }
157 4
        if ($this->length !== null && $length !== $this->length) {
158 1
            return [$this->notEqual, ['length' => $this->length]];
159
        }
160
161 4
        return null;
162
    }
163
164
    /**
165
     * {@inheritdoc}
166
     */
167
    public function clientValidateAttribute($model, $attribute, $view)
168
    {
169
        ValidationAsset::register($view);
170
        $options = $this->getClientOptions($model, $attribute);
171
172
        return 'yii.validation.string(value, messages, ' . Json::htmlEncode($options) . ');';
173
    }
174
175
    /**
176
     * {@inheritdoc}
177
     */
178
    public function getClientOptions($model, $attribute)
179
    {
180
        $label = $model->getAttributeLabel($attribute);
181
182
        $options = [
183
            'message' => $this->formatMessage($this->message, [
184
                'attribute' => $label,
185
            ]),
186
        ];
187
188
        if ($this->min !== null) {
189
            $options['min'] = $this->min;
190
            $options['tooShort'] = $this->formatMessage($this->tooShort, [
191
                'attribute' => $label,
192
                'min' => $this->min,
193
            ]);
194
        }
195
        if ($this->max !== null) {
196
            $options['max'] = $this->max;
197
            $options['tooLong'] = $this->formatMessage($this->tooLong, [
198
                'attribute' => $label,
199
                'max' => $this->max,
200
            ]);
201
        }
202
        if ($this->length !== null) {
203
            $options['is'] = $this->length;
204
            $options['notEqual'] = $this->formatMessage($this->notEqual, [
205
                'attribute' => $label,
206
                'length' => $this->length,
207
            ]);
208
        }
209
        if ($this->skipOnEmpty) {
210
            $options['skipOnEmpty'] = 1;
211
        }
212
213
        return $options;
214
    }
215
216
    /**
217
     * {@inheritdoc}
218
     */
219 26
    public function isEmpty($value)
220
    {
221 26
        if ($this->isEmpty !== null) {
222
            return call_user_func($this->isEmpty, $value);
223
        }
224
225 26
        return $value === null || $value === '';
226
    }
227
}
228