Passed
Pull Request — master (#20134)
by Wilmer
10:17 queued 29s
created

StringValidator::init()   C

Complexity

Conditions 13
Paths 240

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 13

Importance

Changes 0
Metric Value
cc 13
eloc 17
nc 240
nop 0
dl 0
loc 26
ccs 18
cts 18
cp 1
crap 13
rs 5.2833
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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