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

StringValidator::validateValue()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 8

Importance

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