Completed
Push — 2.1 ( 7c8525...0afc41 )
by Alexander
21:05 queued 16:02
created

Validator::setAttributeNames()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 1
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\Component;
12
use yii\base\NotSupportedException;
13
use yii\captcha\CaptchaValidator;
14
15
/**
16
 * Validator is the base class for all validators.
17
 *
18
 * Child classes should override the [[validateValue()]] and/or [[validateAttribute()]] methods to provide the actual
19
 * logic of performing data validation. Child classes may also override [[clientValidateAttribute()]]
20
 * to provide client-side validation support.
21
 *
22
 * Validator declares a set of [[builtInValidators|built-in validators]] which can
23
 * be referenced using short names. They are listed as follows:
24
 *
25
 * - `boolean`: [[BooleanValidator]]
26
 * - `captcha`: [[\yii\captcha\CaptchaValidator]]
27
 * - `compare`: [[CompareValidator]]
28
 * - `date`: [[DateValidator]]
29
 * - `datetime`: [[DateValidator]]
30
 * - `time`: [[DateValidator]]
31
 * - `default`: [[DefaultValueValidator]]
32
 * - `double`: [[NumberValidator]]
33
 * - `each`: [[EachValidator]]
34
 * - `email`: [[EmailValidator]]
35
 * - `exist`: [[ExistValidator]]
36
 * - `file`: [[FileValidator]]
37
 * - `filter`: [[FilterValidator]]
38
 * - `image`: [[ImageValidator]]
39
 * - `in`: [[RangeValidator]]
40
 * - `integer`: [[NumberValidator]]
41
 * - `match`: [[RegularExpressionValidator]]
42
 * - `required`: [[RequiredValidator]]
43
 * - `safe`: [[SafeValidator]]
44
 * - `string`: [[StringValidator]]
45
 * - `trim`: [[FilterValidator]]
46
 * - `unique`: [[UniqueValidator]]
47
 * - `url`: [[UrlValidator]]
48
 * - `ip`: [[IpValidator]]
49
 *
50
 * For more details and usage information on Validator, see the [guide article on validators](guide:input-validation).
51
 *
52
 * @property array $attributeNames Attribute names. This property is read-only.
53
 *
54
 * @author Qiang Xue <[email protected]>
55
 * @since 2.0
56
 */
57
class Validator extends Component
58
{
59
    /**
60
     * @var array list of built-in validators (name => class or configuration)
61
     */
62
    public static $builtInValidators = [
63
        'boolean' => BooleanValidator::class,
64
        'captcha' => CaptchaValidator::class,
65
        'compare' => CompareValidator::class,
66
        'date' => DateValidator::class,
67
        'datetime' => [
68
            'class' => DateValidator::class,
69
            'type' => DateValidator::TYPE_DATETIME,
70
        ],
71
        'time' => [
72
            'class' => DateValidator::class,
73
            'type' => DateValidator::TYPE_TIME,
74
        ],
75
        'default' => DefaultValueValidator::class,
76
        'double' => NumberValidator::class,
77
        'each' => EachValidator::class,
78
        'email' => EmailValidator::class,
79
        'exist' => ExistValidator::class,
80
        'file' => FileValidator::class,
81
        'filter' => FilterValidator::class,
82
        'image' => ImageValidator::class,
83
        'in' => RangeValidator::class,
84
        'integer' => [
85
            'class' => NumberValidator::class,
86
            'integerOnly' => true,
87
        ],
88
        'match' => RegularExpressionValidator::class,
89
        'number' => NumberValidator::class,
90
        'required' => RequiredValidator::class,
91
        'safe' => SafeValidator::class,
92
        'string' => StringValidator::class,
93
        'trim' => [
94
            'class' => FilterValidator::class,
95
            'filter' => 'trim',
96
            'skipOnArray' => true,
97
        ],
98
        'unique' => UniqueValidator::class,
99
        'url' => UrlValidator::class,
100
        'ip' => IpValidator::class,
101
    ];
102
    /**
103
     * @var array|string attributes to be validated by this validator. For multiple attributes,
104
     * please specify them as an array; for single attribute, you may use either a string or an array.
105
     */
106
    public $attributes = [];
107
    /**
108
     * @var string the user-defined error message. It may contain the following placeholders which
109
     * will be replaced accordingly by the validator:
110
     *
111
     * - `{attribute}`: the label of the attribute being validated
112
     * - `{value}`: the value of the attribute being validated
113
     *
114
     * Note that some validators may introduce other properties for error messages used when specific
115
     * validation conditions are not met. Please refer to individual class API documentation for details
116
     * about these properties. By convention, this property represents the primary error message
117
     * used when the most important validation condition is not met.
118
     */
119
    public $message;
120
    /**
121
     * @var array|string scenarios that the validator can be applied to. For multiple scenarios,
122
     * please specify them as an array; for single scenario, you may use either a string or an array.
123
     */
124
    public $on = [];
125
    /**
126
     * @var array|string scenarios that the validator should not be applied to. For multiple scenarios,
127
     * please specify them as an array; for single scenario, you may use either a string or an array.
128
     */
129
    public $except = [];
130
    /**
131
     * @var bool whether this validation rule should be skipped if the attribute being validated
132
     * already has some validation error according to some previous rules. Defaults to true.
133
     */
134
    public $skipOnError = true;
135
    /**
136
     * @var bool whether this validation rule should be skipped if the attribute value
137
     * is null or an empty string.
138
     */
139
    public $skipOnEmpty = true;
140
    /**
141
     * @var bool whether to enable client-side validation for this validator.
142
     * The actual client-side validation is done via the JavaScript code returned
143
     * by [[clientValidateAttribute()]]. If that method returns null, even if this property
144
     * is true, no client-side validation will be done by this validator.
145
     */
146
    public $enableClientValidation = true;
147
    /**
148
     * @var callable a PHP callable that replaces the default implementation of [[isEmpty()]].
149
     * If not set, [[isEmpty()]] will be used to check if a value is empty. The signature
150
     * of the callable should be `function ($value)` which returns a boolean indicating
151
     * whether the value is empty.
152
     */
153
    public $isEmpty;
154
    /**
155
     * @var callable a PHP callable whose return value determines whether this validator should be applied.
156
     * The signature of the callable should be `function ($model, $attribute)`, where `$model` and `$attribute`
157
     * refer to the model and the attribute currently being validated. The callable should return a boolean value.
158
     *
159
     * This property is mainly provided to support conditional validation on the server-side.
160
     * If this property is not set, this validator will be always applied on the server-side.
161
     *
162
     * The following example will enable the validator only when the country currently selected is USA:
163
     *
164
     * ```php
165
     * function ($model) {
166
     *     return $model->country == Country::USA;
167
     * }
168
     * ```
169
     *
170
     * @see whenClient
171
     */
172
    public $when;
173
    /**
174
     * @var string a JavaScript function name whose return value determines whether this validator should be applied
175
     * on the client-side. The signature of the function should be `function (attribute, value)`, where
176
     * `attribute` is an object describing the attribute being validated (see [[clientValidateAttribute()]])
177
     * and `value` the current value of the attribute.
178
     *
179
     * This property is mainly provided to support conditional validation on the client-side.
180
     * If this property is not set, this validator will be always applied on the client-side.
181
     *
182
     * The following example will enable the validator only when the country currently selected is USA:
183
     *
184
     * ```javascript
185
     * function (attribute, value) {
186
     *     return $('#country').val() === 'USA';
187
     * }
188
     * ```
189
     *
190
     * @see when
191
     */
192
    public $whenClient;
193
194
195
    /**
196
     * Creates a validator object.
197
     * @param string|\Closure $type the validator type. This can be either:
198
     *  * a built-in validator name listed in [[builtInValidators]];
199
     *  * a method name of the model class;
200
     *  * an anonymous function;
201
     *  * a validator class name.
202
     * @param \yii\base\Model $model the data model to be validated.
203
     * @param array|string $attributes list of attributes to be validated. This can be either an array of
204
     * the attribute names or a string of comma-separated attribute names.
205
     * @param array $params initial values to be applied to the validator properties.
206
     * @return Validator the validator
207
     */
208 42
    public static function createValidator($type, $model, $attributes, $params = [])
209
    {
210 42
        $params['attributes'] = $attributes;
211
212 42
        if ($type instanceof \Closure || $model->hasMethod($type)) {
213
            // method-based validator
214 3
            $params['class'] = __NAMESPACE__ . '\InlineValidator';
215 3
            $params['method'] = $type;
216
        } else {
217 40
            if (isset(static::$builtInValidators[$type])) {
218 36
                $type = static::$builtInValidators[$type];
219
            }
220 40
            if (is_array($type)) {
221 11
                $params = array_merge($type, $params);
222
            } else {
223 34
                $params['class'] = $type;
224
            }
225
        }
226
227 42
        return Yii::createObject($params);
228
    }
229
230
    /**
231
     * @inheritdoc
232
     */
233 395
    public function init()
234
    {
235 395
        parent::init();
236 395
        $this->attributes = (array) $this->attributes;
237 395
        $this->on = (array) $this->on;
238 395
        $this->except = (array) $this->except;
239 395
    }
240
241
    /**
242
     * Validates the specified object.
243
     * @param \yii\base\Model $model the data model being validated
244
     * @param array|null $attributes the list of attributes to be validated.
245
     * Note that if an attribute is not associated with the validator - it will be
246
     * ignored. If this parameter is null, every attribute listed in [[attributes]] will be validated.
247
     */
248 18
    public function validateAttributes($model, $attributes = null)
249
    {
250 18
        if (is_array($attributes)) {
251 16
            $newAttributes = [];
252 16
            foreach ($attributes as $attribute) {
253 16
                if (in_array($attribute, $this->getAttributeNames(), true)) {
254 15
                    $newAttributes[] = $attribute;
255
                }
256
            }
257 16
            $attributes = $newAttributes;
258
        } else {
259 4
            $attributes = $this->getAttributeNames();
260
        }
261
262 18
        foreach ($attributes as $attribute) {
263 17
            $skip = $this->skipOnError && $model->hasErrors($attribute)
264 17
                || $this->skipOnEmpty && $this->isEmpty($model->$attribute);
265 17
            if (!$skip) {
266 12
                if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
267 12
                    $this->validateAttribute($model, $attribute);
268
                }
269
            }
270
        }
271 18
    }
272
273
    /**
274
     * Validates a single attribute.
275
     * Child classes must implement this method to provide the actual validation logic.
276
     * @param \yii\base\Model $model the data model to be validated
277
     * @param string $attribute the name of the attribute to be validated.
278
     */
279 12
    public function validateAttribute($model, $attribute)
280
    {
281 12
        $result = $this->validateValue($model->$attribute);
282 12
        if (!empty($result)) {
283 7
            $this->addError($model, $attribute, $result[0], $result[1]);
284
        }
285 12
    }
286
287
    /**
288
     * Validates a given value.
289
     * You may use this method to validate a value out of the context of a data model.
290
     * @param mixed $value the data value to be validated.
291
     * @param string $error the error message to be returned, if the validation fails.
292
     * @return bool whether the data is valid.
293
     */
294 96
    public function validate($value, &$error = null)
295
    {
296 96
        $result = $this->validateValue($value);
297 91
        if (empty($result)) {
298 59
            return true;
299
        }
300
301 79
        list($message, $params) = $result;
302 79
        $params['attribute'] = Yii::t('yii', 'the input value');
303 79
        if (is_array($value)) {
304 12
            $params['value'] = 'array()';
305 74
        } elseif (is_object($value)) {
306 5
            $params['value'] = 'object';
307
        } else {
308 69
            $params['value'] = $value;
309
        }
310 79
        $error = $this->formatMessage($message, $params);
311
312 79
        return false;
313
    }
314
315
    /**
316
     * Validates a value.
317
     * A validator class can implement this method to support data validation out of the context of a data model.
318
     * @param mixed $value the data value to be validated.
319
     * @return array|null the error message and the parameters to be inserted into the error message.
320
     * Null should be returned if the data is valid.
321
     * @throws NotSupportedException if the validator does not supporting data validation without a model
322
     */
323 1
    protected function validateValue($value)
324
    {
325 1
        throw new NotSupportedException(get_class($this) . ' does not support validateValue().');
326
    }
327
328
    /**
329
     * Returns the JavaScript needed for performing client-side validation.
330
     *
331
     * Calls [[getClientOptions()]] to generate options array for client-side validation.
332
     *
333
     * You may override this method to return the JavaScript validation code if
334
     * the validator can support client-side validation.
335
     *
336
     * The following JavaScript variables are predefined and can be used in the validation code:
337
     *
338
     * - `attribute`: an object describing the the attribute being validated.
339
     * - `value`: the value being validated.
340
     * - `messages`: an array used to hold the validation error messages for the attribute.
341
     * - `deferred`: an array used to hold deferred objects for asynchronous validation
342
     * - `$form`: a jQuery object containing the form element
343
     *
344
     * The `attribute` object contains the following properties:
345
     * - `id`: a unique ID identifying the attribute (e.g. "loginform-username") in the form
346
     * - `name`: attribute name or expression (e.g. "[0]content" for tabular input)
347
     * - `container`: the jQuery selector of the container of the input field
348
     * - `input`: the jQuery selector of the input field under the context of the form
349
     * - `error`: the jQuery selector of the error tag under the context of the container
350
     * - `status`: status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
351
     *
352
     * @param \yii\base\Model $model the data model being validated
353
     * @param string $attribute the name of the attribute to be validated.
354
     * @param \yii\web\View $view the view object that is going to be used to render views or view files
355
     * containing a model form with this validator applied.
356
     * @return string|null the client-side validation script. Null if the validator does not support
357
     * client-side validation.
358
     * @see getClientOptions()
359
     * @see \yii\widgets\ActiveForm::enableClientValidation
360
     */
361 1
    public function clientValidateAttribute($model, $attribute, $view)
362
    {
363 1
        return null;
364
    }
365
366
    /**
367
     * Returns the client-side validation options.
368
     * This method is usually called from [[clientValidateAttribute()]]. You may override this method to modify options
369
     * that will be passed to the client-side validation.
370
     * @param \yii\base\Model $model the model being validated
371
     * @param string $attribute the attribute name being validated
372
     * @return array the client-side validation options
373
     * @since 2.0.11
374
     */
375
    public function getClientOptions($model, $attribute)
376
    {
377
        return [];
378
    }
379
380
    /**
381
     * Returns a value indicating whether the validator is active for the given scenario and attribute.
382
     *
383
     * A validator is active if
384
     *
385
     * - the validator's `on` property is empty, or
386
     * - the validator's `on` property contains the specified scenario
387
     *
388
     * @param string $scenario scenario name
389
     * @return bool whether the validator applies to the specified scenario.
390
     */
391 26
    public function isActive($scenario)
392
    {
393 26
        return !in_array($scenario, $this->except, true) && (empty($this->on) || in_array($scenario, $this->on, true));
394
    }
395
396
    /**
397
     * Adds an error about the specified attribute to the model object.
398
     * This is a helper method that performs message selection and internationalization.
399
     * @param \yii\base\Model $model the data model being validated
400
     * @param string $attribute the attribute being validated
401
     * @param string $message the error message
402
     * @param array $params values for the placeholders in the error message
403
     */
404 95
    public function addError($model, $attribute, $message, $params = [])
405
    {
406 95
        $params['attribute'] = $model->getAttributeLabel($attribute);
407 95
        if (!isset($params['value'])) {
408 95
            $value = $model->$attribute;
409 95
            if (is_array($value)) {
410 28
                $params['value'] = 'array()';
411 93
            } elseif (is_object($value) && !method_exists($value, '__toString')) {
412 1
                $params['value'] = '(object)';
413
            } else {
414 93
                $params['value'] = $value;
415
            }
416
        }
417 95
        $model->addError($attribute, $this->formatMessage($message, $params));
418 95
    }
419
420
    /**
421
     * Checks if the given value is empty.
422
     * A value is considered empty if it is null, an empty array, or an empty string.
423
     * Note that this method is different from PHP empty(). It will return false when the value is 0.
424
     * @param mixed $value the value to be checked
425
     * @return bool whether the value is empty
426
     */
427 166
    public function isEmpty($value)
428
    {
429 166
        if ($this->isEmpty !== null) {
430
            return call_user_func($this->isEmpty, $value);
431
        } else {
432 166
            return $value === null || $value === [] || $value === '';
433
        }
434
    }
435
436
    /**
437
     * Formats a mesage using the I18N, or simple strtr if `\Yii::$app` is not available.
438
     * @param string $message
439
     * @param array $params
440
     * @since 2.0.12
441
     * @return string
442
     */
443 174
    protected function formatMessage($message, $params)
444
    {
445 174
        if (Yii::$app !== null) {
446 50
            return \Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
447
        }
448
449 124
        $placeholders = [];
450 124
        foreach ((array) $params as $name => $value) {
451 124
            $placeholders['{' . $name . '}'] = $value;
452
        }
453
454 124
        return ($placeholders === []) ? $message : strtr($message, $placeholders);
455
    }
456
457
    /**
458
     * Returns cleaned attribute names without the `!` character at the beginning
459
     * @return array attribute names.
460
     * @since 2.0.12
461
     */
462
    public function getAttributeNames()
463
    {
464 30
        return array_map(function($attribute) {
465 29
            return ltrim($attribute, '!');
466 30
        }, $this->attributes);
467
    }
468
}
469