Passed
Push — master ( b1e51d...f3473a )
by Paweł
20:17
created

Model::beforeValidate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 6
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
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\base;
9
10
use ArrayAccess;
11
use ArrayIterator;
12
use ArrayObject;
13
use IteratorAggregate;
14
use ReflectionClass;
15
use Yii;
16
use yii\helpers\Inflector;
17
use yii\validators\RequiredValidator;
18
use yii\validators\Validator;
19
20
/**
21
 * Model is the base class for data models.
22
 *
23
 * Model implements the following commonly used features:
24
 *
25
 * - attribute declaration: by default, every public class member is considered as
26
 *   a model attribute
27
 * - attribute labels: each attribute may be associated with a label for display purpose
28
 * - massive attribute assignment
29
 * - scenario-based validation
30
 *
31
 * Model also raises the following events when performing data validation:
32
 *
33
 * - [[EVENT_BEFORE_VALIDATE]]: an event raised at the beginning of [[validate()]]
34
 * - [[EVENT_AFTER_VALIDATE]]: an event raised at the end of [[validate()]]
35
 *
36
 * You may directly use Model to store model data, or extend it with customization.
37
 *
38
 * For more details and usage information on Model, see the [guide article on models](guide:structure-models).
39
 *
40
 * @property-read \yii\validators\Validator[] $activeValidators The validators applicable to the current
41
 * [[scenario]].
42
 * @property array $attributes Attribute values (name => value).
43
 * @property-read array $errors Errors for all attributes or the specified attribute. Empty array is returned
44
 * if no error. See [[getErrors()]] for detailed description. Note that when returning errors for all attributes,
45
 * the result is a two-dimensional array, like the following: ```php [ 'username' => [ 'Username is required.',
46
 * 'Username must contain only word characters.', ], 'email' => [ 'Email address is invalid.', ] ] ``` .
47
 * @property-read array $firstErrors The first errors. The array keys are the attribute names, and the array
48
 * values are the corresponding error messages. An empty array will be returned if there is no error.
49
 * @property-read ArrayIterator $iterator An iterator for traversing the items in the list.
50
 * @property string $scenario The scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
51
 * @property-read ArrayObject|\yii\validators\Validator[] $validators All the validators declared in the
52
 * model.
53
 *
54
 * @author Qiang Xue <[email protected]>
55
 * @since 2.0
56
 */
57
class Model extends Component implements StaticInstanceInterface, IteratorAggregate, ArrayAccess, Arrayable
58
{
59
    use ArrayableTrait;
60
    use StaticInstanceTrait;
61
62
    /**
63
     * The name of the default scenario.
64
     */
65
    const SCENARIO_DEFAULT = 'default';
66
    /**
67
     * @event ModelEvent an event raised at the beginning of [[validate()]]. You may set
68
     * [[ModelEvent::isValid]] to be false to stop the validation.
69
     */
70
    const EVENT_BEFORE_VALIDATE = 'beforeValidate';
71
    /**
72
     * @event Event an event raised at the end of [[validate()]]
73
     */
74
    const EVENT_AFTER_VALIDATE = 'afterValidate';
75
76
    /**
77
     * @var array validation errors (attribute name => array of errors)
78
     */
79
    private $_errors;
80
    /**
81
     * @var ArrayObject list of validators
82
     */
83
    private $_validators;
84
    /**
85
     * @var string current scenario
86
     */
87
    private $_scenario = self::SCENARIO_DEFAULT;
88
89
90
    /**
91
     * Returns the validation rules for attributes.
92
     *
93
     * Validation rules are used by [[validate()]] to check if attribute values are valid.
94
     * Child classes may override this method to declare different validation rules.
95
     *
96
     * Each rule is an array with the following structure:
97
     *
98
     * ```php
99
     * [
100
     *     ['attribute1', 'attribute2'],
101
     *     'validator type',
102
     *     'on' => ['scenario1', 'scenario2'],
103
     *     //...other parameters...
104
     * ]
105
     * ```
106
     *
107
     * where
108
     *
109
     *  - attribute list: required, specifies the attributes array to be validated, for single attribute you can pass a string;
110
     *  - validator type: required, specifies the validator to be used. It can be a built-in validator name,
111
     *    a method name of the model class, an anonymous function, or a validator class name.
112
     *  - on: optional, specifies the [[scenario|scenarios]] array in which the validation
113
     *    rule can be applied. If this option is not set, the rule will apply to all scenarios.
114
     *  - additional name-value pairs can be specified to initialize the corresponding validator properties.
115
     *    Please refer to individual validator class API for possible properties.
116
     *
117
     * A validator can be either an object of a class extending [[Validator]], or a model class method
118
     * (called *inline validator*) that has the following signature:
119
     *
120
     * ```php
121
     * // $params refers to validation parameters given in the rule
122
     * function validatorName($attribute, $params)
123
     * ```
124
     *
125
     * In the above `$attribute` refers to the attribute currently being validated while `$params` contains an array of
126
     * validator configuration options such as `max` in case of `string` validator. The value of the attribute currently being validated
127
     * can be accessed as `$this->$attribute`. Note the `$` before `attribute`; this is taking the value of the variable
128
     * `$attribute` and using it as the name of the property to access.
129
     *
130
     * Yii also provides a set of [[Validator::builtInValidators|built-in validators]].
131
     * Each one has an alias name which can be used when specifying a validation rule.
132
     *
133
     * Below are some examples:
134
     *
135
     * ```php
136
     * [
137
     *     // built-in "required" validator
138
     *     [['username', 'password'], 'required'],
139
     *     // built-in "string" validator customized with "min" and "max" properties
140
     *     ['username', 'string', 'min' => 3, 'max' => 12],
141
     *     // built-in "compare" validator that is used in "register" scenario only
142
     *     ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
143
     *     // an inline validator defined via the "authenticate()" method in the model class
144
     *     ['password', 'authenticate', 'on' => 'login'],
145
     *     // a validator of class "DateRangeValidator"
146
     *     ['dateRange', 'DateRangeValidator'],
147
     * ];
148
     * ```
149
     *
150
     * Note, in order to inherit rules defined in the parent class, a child class needs to
151
     * merge the parent rules with child rules using functions such as `array_merge()`.
152
     *
153
     * @return array validation rules
154
     * @see scenarios()
155
     */
156
    public function rules()
157 137
    {
158
        return [];
159 137
    }
160
161
    /**
162
     * Returns a list of scenarios and the corresponding active attributes.
163
     *
164
     * An active attribute is one that is subject to validation in the current scenario.
165
     * The returned array should be in the following format:
166
     *
167
     * ```php
168
     * [
169
     *     'scenario1' => ['attribute11', 'attribute12', ...],
170
     *     'scenario2' => ['attribute21', 'attribute22', ...],
171
     *     ...
172
     * ]
173
     * ```
174
     *
175
     * By default, an active attribute is considered safe and can be massively assigned.
176
     * If an attribute should NOT be massively assigned (thus considered unsafe),
177
     * please prefix the attribute with an exclamation character (e.g. `'!rank'`).
178
     *
179
     * The default implementation of this method will return all scenarios found in the [[rules()]]
180
     * declaration. A special scenario named [[SCENARIO_DEFAULT]] will contain all attributes
181
     * found in the [[rules()]]. Each scenario will be associated with the attributes that
182
     * are being validated by the validation rules that apply to the scenario.
183
     *
184
     * @return array a list of scenarios and the corresponding active attributes.
185
     */
186
    public function scenarios()
187 149
    {
188
        $scenarios = [self::SCENARIO_DEFAULT => []];
189 149
        foreach ($this->getValidators() as $validator) {
190 149
            foreach ($validator->on as $scenario) {
191 79
                $scenarios[$scenario] = [];
192 6
            }
193
            foreach ($validator->except as $scenario) {
194 79
                $scenarios[$scenario] = [];
195 79
            }
196
        }
197
        $names = array_keys($scenarios);
198 149
199
        foreach ($this->getValidators() as $validator) {
200 149
            if (empty($validator->on) && empty($validator->except)) {
201 79
                foreach ($names as $name) {
202 79
                    foreach ($validator->attributes as $attribute) {
203 79
                        $scenarios[$name][$attribute] = true;
204 79
                    }
205
                }
206
            } elseif (empty($validator->on)) {
207 6
                foreach ($names as $name) {
208 2
                    if (!in_array($name, $validator->except, true)) {
209 2
                        foreach ($validator->attributes as $attribute) {
210 2
                            $scenarios[$name][$attribute] = true;
211 2
                        }
212
                    }
213
                }
214
            } else {
215
                foreach ($validator->on as $name) {
216 6
                    foreach ($validator->attributes as $attribute) {
217 6
                        $scenarios[$name][$attribute] = true;
218 79
                    }
219
                }
220
            }
221
        }
222
223
        foreach ($scenarios as $scenario => $attributes) {
224 149
            if (!empty($attributes)) {
225 149
                $scenarios[$scenario] = array_keys($attributes);
226 149
            }
227
        }
228
229
        return $scenarios;
230 149
    }
231
232
    /**
233
     * Returns the form name that this model class should use.
234
     *
235
     * The form name is mainly used by [[\yii\widgets\ActiveForm]] to determine how to name
236
     * the input fields for the attributes in a model. If the form name is "A" and an attribute
237
     * name is "b", then the corresponding input name would be "A[b]". If the form name is
238
     * an empty string, then the input name would be "b".
239
     *
240
     * The purpose of the above naming schema is that for forms which contain multiple different models,
241
     * the attributes of each model are grouped in sub-arrays of the POST-data and it is easier to
242
     * differentiate between them.
243
     *
244
     * By default, this method returns the model class name (without the namespace part)
245
     * as the form name. You may override it when the model is used in different forms.
246
     *
247
     * @return string the form name of this model class.
248
     * @see load()
249
     * @throws InvalidConfigException when form is defined with anonymous class and `formName()` method is
250
     * not overridden.
251
     */
252
    public function formName()
253 86
    {
254
        $reflector = new ReflectionClass($this);
255 86
        if (PHP_VERSION_ID >= 70000 && $reflector->isAnonymous()) {
256 86
            throw new InvalidConfigException('The "formName()" method should be explicitly defined for anonymous models');
257 1
        }
258
        return $reflector->getShortName();
259 85
    }
260
261
    /**
262
     * Returns the list of attribute names.
263
     * By default, this method returns all public non-static properties of the class.
264
     * You may override this method to change the default behavior.
265
     * @return array list of attribute names.
266
     */
267
    public function attributes()
268 8
    {
269
        $class = new ReflectionClass($this);
270 8
        $names = [];
271 8
        foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
272 8
            if (!$property->isStatic()) {
273 8
                $names[] = $property->getName();
274 8
            }
275
        }
276
277
        return $names;
278 8
    }
279
280
    /**
281
     * Returns the attribute labels.
282
     *
283
     * Attribute labels are mainly used for display purpose. For example, given an attribute
284
     * `firstName`, we can declare a label `First Name` which is more user-friendly and can
285
     * be displayed to end users.
286
     *
287
     * By default an attribute label is generated using [[generateAttributeLabel()]].
288
     * This method allows you to explicitly specify attribute labels.
289
     *
290
     * Note, in order to inherit labels defined in the parent class, a child class needs to
291
     * merge the parent labels with child labels using functions such as `array_merge()`.
292
     *
293
     * @return array attribute labels (name => label)
294
     * @see generateAttributeLabel()
295
     */
296
    public function attributeLabels()
297 125
    {
298
        return [];
299 125
    }
300
301
    /**
302
     * Returns the attribute hints.
303
     *
304
     * Attribute hints are mainly used for display purpose. For example, given an attribute
305
     * `isPublic`, we can declare a hint `Whether the post should be visible for not logged in users`,
306
     * which provides user-friendly description of the attribute meaning and can be displayed to end users.
307
     *
308
     * Unlike label hint will not be generated, if its explicit declaration is omitted.
309
     *
310
     * Note, in order to inherit hints defined in the parent class, a child class needs to
311
     * merge the parent hints with child hints using functions such as `array_merge()`.
312
     *
313
     * @return array attribute hints (name => hint)
314
     * @since 2.0.4
315
     */
316
    public function attributeHints()
317 4
    {
318
        return [];
319 4
    }
320
321
    /**
322
     * Performs the data validation.
323
     *
324
     * This method executes the validation rules applicable to the current [[scenario]].
325
     * The following criteria are used to determine whether a rule is currently applicable:
326
     *
327
     * - the rule must be associated with the attributes relevant to the current scenario;
328
     * - the rules must be effective for the current scenario.
329
     *
330
     * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
331
     * after the actual validation, respectively. If [[beforeValidate()]] returns false,
332
     * the validation will be cancelled and [[afterValidate()]] will not be called.
333
     *
334
     * Errors found during the validation can be retrieved via [[getErrors()]],
335
     * [[getFirstErrors()]] and [[getFirstError()]].
336
     *
337
     * @param string[]|string|null $attributeNames attribute name or list of attribute names
338
     * that should be validated. If this parameter is empty, it means any attribute listed in
339
     * the applicable validation rules should be validated.
340
     * @param bool $clearErrors whether to call [[clearErrors()]] before performing validation
341
     * @return bool whether the validation is successful without any error.
342
     * @throws InvalidArgumentException if the current scenario is unknown.
343
     */
344
    public function validate($attributeNames = null, $clearErrors = true)
345 106
    {
346
        if ($clearErrors) {
347 106
            $this->clearErrors();
348 97
        }
349
350
        if (!$this->beforeValidate()) {
351 106
            return false;
352
        }
353
354
        $scenarios = $this->scenarios();
355 106
        $scenario = $this->getScenario();
356 106
        if (!isset($scenarios[$scenario])) {
357 106
            throw new InvalidArgumentException("Unknown scenario: $scenario");
358
        }
359
360
        if ($attributeNames === null) {
361 106
            $attributeNames = $this->activeAttributes();
362 105
        }
363
364
        $attributeNames = (array)$attributeNames;
365 106
366
        foreach ($this->getActiveValidators() as $validator) {
367 106
            $validator->validateAttributes($this, $attributeNames);
368 59
        }
369
        $this->afterValidate();
370 106
371
        return !$this->hasErrors();
372 106
    }
373
374
    /**
375
     * This method is invoked before validation starts.
376
     * The default implementation raises a `beforeValidate` event.
377
     * You may override this method to do preliminary checks before validation.
378
     * Make sure the parent implementation is invoked so that the event can be raised.
379
     * @return bool whether the validation should be executed. Defaults to true.
380
     * If false is returned, the validation will stop and the model is considered invalid.
381
     */
382
    public function beforeValidate()
383 107
    {
384
        $event = new ModelEvent();
385 107
        $this->trigger(self::EVENT_BEFORE_VALIDATE, $event);
386 107
387
        return $event->isValid;
388 107
    }
389
390
    /**
391
     * This method is invoked after validation ends.
392
     * The default implementation raises an `afterValidate` event.
393
     * You may override this method to do postprocessing after validation.
394
     * Make sure the parent implementation is invoked so that the event can be raised.
395
     */
396
    public function afterValidate()
397 106
    {
398
        $this->trigger(self::EVENT_AFTER_VALIDATE);
399 106
    }
400 106
401
    /**
402
     * Returns all the validators declared in [[rules()]].
403
     *
404
     * This method differs from [[getActiveValidators()]] in that the latter
405
     * only returns the validators applicable to the current [[scenario]].
406
     *
407
     * Because this method returns an ArrayObject object, you may
408
     * manipulate it by inserting or removing validators (useful in model behaviors).
409
     * For example,
410
     *
411
     * ```php
412
     * $model->validators[] = $newValidator;
413
     * ```
414
     *
415
     * @return ArrayObject|\yii\validators\Validator[] all the validators declared in the model.
416
     */
417
    public function getValidators()
418 166
    {
419
        if ($this->_validators === null) {
420 166
            $this->_validators = $this->createValidators();
421 166
        }
422
423
        return $this->_validators;
424 166
    }
425
426
    /**
427
     * Returns the validators applicable to the current [[scenario]].
428
     * @param string|null $attribute the name of the attribute whose applicable validators should be returned.
429
     * If this is null, the validators for ALL attributes in the model will be returned.
430
     * @return \yii\validators\Validator[] the validators applicable to the current [[scenario]].
431
     */
432
    public function getActiveValidators($attribute = null)
433 144
    {
434
        $activeAttributes = $this->activeAttributes();
435 144
        if ($attribute !== null && !in_array($attribute, $activeAttributes, true)) {
436 144
            return [];
437 24
        }
438
        $scenario = $this->getScenario();
439 122
        $validators = [];
440 122
        foreach ($this->getValidators() as $validator) {
441 122
            if ($attribute === null) {
442 75
                $validatorAttributes = $validator->getValidationAttributes($activeAttributes);
443 60
                $attributeValid = !empty($validatorAttributes);
444 60
            } else {
445
                $attributeValid = in_array($attribute, $validator->getValidationAttributes($attribute), true);
446 16
            }
447
            if ($attributeValid && $validator->isActive($scenario)) {
448 75
                $validators[] = $validator;
449 75
            }
450
        }
451
452
        return $validators;
453 122
    }
454
455
    /**
456
     * Creates validator objects based on the validation rules specified in [[rules()]].
457
     * Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned.
458
     * @return ArrayObject validators
459
     * @throws InvalidConfigException if any validation rule configuration is invalid
460
     */
461
    public function createValidators()
462 167
    {
463
        $validators = new ArrayObject();
464 167
        foreach ($this->rules() as $rule) {
465 167
            if ($rule instanceof Validator) {
466 60
                $validators->append($rule);
467
            } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
468 60
                $validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2));
469 59
                $validators->append($validator);
470 59
            } else {
471
                throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
472 60
            }
473
        }
474
475
        return $validators;
476 166
    }
477
478
    /**
479
     * Returns a value indicating whether the attribute is required.
480
     * This is determined by checking if the attribute is associated with a
481
     * [[\yii\validators\RequiredValidator|required]] validation rule in the
482
     * current [[scenario]].
483
     *
484
     * Note that when the validator has a conditional validation applied using
485
     * [[\yii\validators\RequiredValidator::$when|$when]] this method will return
486
     * `false` regardless of the `when` condition because it may be called be
487
     * before the model is loaded with data.
488
     *
489
     * @param string $attribute attribute name
490
     * @return bool whether the attribute is required
491
     */
492
    public function isAttributeRequired($attribute)
493 27
    {
494
        foreach ($this->getActiveValidators($attribute) as $validator) {
495 27
            if ($validator instanceof RequiredValidator && $validator->when === null) {
496 5
                return true;
497 5
            }
498
        }
499
500
        return false;
501 24
    }
502
503
    /**
504
     * Returns a value indicating whether the attribute is safe for massive assignments.
505
     * @param string $attribute attribute name
506
     * @return bool whether the attribute is safe for massive assignments
507
     * @see safeAttributes()
508
     */
509
    public function isAttributeSafe($attribute)
510 24
    {
511
        return in_array($attribute, $this->safeAttributes(), true);
512 24
    }
513
514
    /**
515
     * Returns a value indicating whether the attribute is active in the current scenario.
516
     * @param string $attribute attribute name
517
     * @return bool whether the attribute is active in the current scenario
518
     * @see activeAttributes()
519
     */
520
    public function isAttributeActive($attribute)
521 4
    {
522
        return in_array($attribute, $this->activeAttributes(), true);
523 4
    }
524
525
    /**
526
     * Returns the text label for the specified attribute.
527
     * @param string $attribute the attribute name
528
     * @return string the attribute label
529
     * @see generateAttributeLabel()
530
     * @see attributeLabels()
531
     */
532
    public function getAttributeLabel($attribute)
533 47
    {
534
        $labels = $this->attributeLabels();
535 47
        return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
536 47
    }
537
538
    /**
539
     * Returns the text hint for the specified attribute.
540
     * @param string $attribute the attribute name
541
     * @return string the attribute hint
542
     * @see attributeHints()
543
     * @since 2.0.4
544
     */
545
    public function getAttributeHint($attribute)
546 13
    {
547
        $hints = $this->attributeHints();
548 13
        return isset($hints[$attribute]) ? $hints[$attribute] : '';
549 13
    }
550
551
    /**
552
     * Returns a value indicating whether there is any validation error.
553
     * @param string|null $attribute attribute name. Use null to check all attributes.
554
     * @return bool whether there is any error.
555
     */
556
    public function hasErrors($attribute = null)
557 435
    {
558
        return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
559 435
    }
560
561
    /**
562
     * Returns the errors for all attributes or a single attribute.
563
     * @param string|null $attribute attribute name. Use null to retrieve errors for all attributes.
564
     * @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
565
     * See [[getErrors()]] for detailed description.
566
     * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
567
     *
568
     * ```php
569
     * [
570
     *     'username' => [
571
     *         'Username is required.',
572
     *         'Username must contain only word characters.',
573
     *     ],
574
     *     'email' => [
575
     *         'Email address is invalid.',
576
     *     ]
577
     * ]
578
     * ```
579
     *
580
     * @see getFirstErrors()
581
     * @see getFirstError()
582
     */
583
    public function getErrors($attribute = null)
584
    {
585 49
        if ($attribute === null) {
586
            return $this->_errors === null ? [] : $this->_errors;
587 49
        }
588 11
589
        return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
590
    }
591 39
592
    /**
593
     * Returns the first error of every attribute in the model.
594
     * @return array the first errors. The array keys are the attribute names, and the array
595
     * values are the corresponding error messages. An empty array will be returned if there is no error.
596
     * @see getErrors()
597
     * @see getFirstError()
598
     */
599
    public function getFirstErrors()
600
    {
601 8
        if (empty($this->_errors)) {
602
            return [];
603 8
        }
604 3
605
        $errors = [];
606
        foreach ($this->_errors as $name => $es) {
607 6
            if (!empty($es)) {
608 6
                $errors[$name] = reset($es);
609 6
            }
610 6
        }
611
612
        return $errors;
613
    }
614 6
615
    /**
616
     * Returns the first error of the specified attribute.
617
     * @param string $attribute attribute name.
618
     * @return string|null the error message. Null is returned if no error.
619
     * @see getErrors()
620
     * @see getFirstErrors()
621
     */
622
    public function getFirstError($attribute)
623
    {
624 43
        return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
625
    }
626 43
627
    /**
628
     * Returns the errors for all attributes as a one-dimensional array.
629
     * @param bool $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
630
     * only the first error message for each attribute will be shown.
631
     * @return array errors for all attributes as a one-dimensional array. Empty array is returned if no error.
632
     * @see getErrors()
633
     * @see getFirstErrors()
634
     * @since 2.0.14
635
     */
636
    public function getErrorSummary($showAllErrors)
637
    {
638 11
        $lines = [];
639
        $errors = $showAllErrors ? $this->getErrors() : $this->getFirstErrors();
640 11
        foreach ($errors as $es) {
641 11
            $lines = array_merge($lines, (array)$es);
642 11
        }
643 9
        return $lines;
644
    }
645 11
646
    /**
647
     * Adds a new error to the specified attribute.
648
     * @param string $attribute attribute name
649
     * @param string $error new error message
650
     */
651
    public function addError($attribute, $error = '')
652
    {
653 172
        $this->_errors[$attribute][] = $error;
654
    }
655 172
656 172
    /**
657
     * Adds a list of errors.
658
     * @param array $items a list of errors. The array keys must be attribute names.
659
     * The array values should be error messages. If an attribute has multiple errors,
660
     * these errors must be given in terms of an array.
661
     * You may use the result of [[getErrors()]] as the value for this parameter.
662
     * @since 2.0.2
663
     */
664
    public function addErrors(array $items)
665
    {
666 7
        foreach ($items as $attribute => $errors) {
667
            if (is_array($errors)) {
668 7
                foreach ($errors as $error) {
669 7
                    $this->addError($attribute, $error);
670 7
                }
671 7
            } else {
672
                $this->addError($attribute, $errors);
673
            }
674 7
        }
675
    }
676
677 7
    /**
678
     * Removes errors for all attributes or a single attribute.
679
     * @param string|null $attribute attribute name. Use null to remove errors for all attributes.
680
     */
681
    public function clearErrors($attribute = null)
682
    {
683 133
        if ($attribute === null) {
684
            $this->_errors = [];
685 133
        } else {
686 127
            unset($this->_errors[$attribute]);
687
        }
688 7
    }
689
690 133
    /**
691
     * Generates a user friendly attribute label based on the give attribute name.
692
     * This is done by replacing underscores, dashes and dots with blanks and
693
     * changing the first letter of each word to upper case.
694
     * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
695
     * @param string $name the column name
696
     * @return string the attribute label
697
     */
698
    public function generateAttributeLabel($name)
699
    {
700 136
        return Inflector::camel2words($name, true);
701
    }
702 136
703
    /**
704
     * Returns attribute values.
705
     * @param array|null $names list of attributes whose value needs to be returned.
706
     * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
707
     * If it is an array, only the attributes in the array will be returned.
708
     * @param array $except list of attributes whose value should NOT be returned.
709
     * @return array attribute values (name => value).
710
     */
711
    public function getAttributes($names = null, $except = [])
712
    {
713 18
        $values = [];
714
        if ($names === null) {
715 18
            $names = $this->attributes();
716 18
        }
717 18
        foreach ($names as $name) {
718
            $values[$name] = $this->$name;
719 18
        }
720 18
        foreach ($except as $name) {
721
            unset($values[$name]);
722 18
        }
723 1
724
        return $values;
725
    }
726 18
727
    /**
728
     * Sets the attribute values in a massive way.
729
     * @param array $values attribute values (name => value) to be assigned to the model.
730
     * @param bool $safeOnly whether the assignments should only be done to the safe attributes.
731
     * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
732
     * @see safeAttributes()
733
     * @see attributes()
734
     */
735
    public function setAttributes($values, $safeOnly = true)
736
    {
737 14
        if (is_array($values)) {
0 ignored issues
show
introduced by
The condition is_array($values) is always true.
Loading history...
738
            $attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
739 14
            foreach ($values as $name => $value) {
740 14
                if (isset($attributes[$name])) {
741 14
                    $this->$name = $value;
742 14
                } elseif ($safeOnly) {
743 14
                    $this->onUnsafeAttribute($name, $value);
744 3
                }
745 14
            }
746
        }
747
    }
748
749 14
    /**
750
     * This method is invoked when an unsafe attribute is being massively assigned.
751
     * The default implementation will log a warning message if YII_DEBUG is on.
752
     * It does nothing otherwise.
753
     * @param string $name the unsafe attribute name
754
     * @param mixed $value the attribute value
755
     */
756
    public function onUnsafeAttribute($name, $value)
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

756
    public function onUnsafeAttribute($name, /** @scrutinizer ignore-unused */ $value)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
757
    {
758 3
        if (YII_DEBUG) {
759
            Yii::debug("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.", __METHOD__);
760 3
        }
761 3
    }
762
763 3
    /**
764
     * Returns the scenario that this model is used in.
765
     *
766
     * Scenario affects how validation is performed and which attributes can
767
     * be massively assigned.
768
     *
769
     * @return string the scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
770
     */
771
    public function getScenario()
772
    {
773 287
        return $this->_scenario;
774
    }
775 287
776
    /**
777
     * Sets the scenario for the model.
778
     * Note that this method does not check if the scenario exists or not.
779
     * The method [[validate()]] will perform this check.
780
     * @param string $value the scenario that this model is in.
781
     */
782
    public function setScenario($value)
783
    {
784 11
        $this->_scenario = $value;
785
    }
786 11
787 11
    /**
788
     * Returns the attribute names that are safe to be massively assigned in the current scenario.
789
     * @return string[] safe attribute names
790
     */
791
    public function safeAttributes()
792
    {
793 32
        $scenario = $this->getScenario();
794
        $scenarios = $this->scenarios();
795 32
        if (!isset($scenarios[$scenario])) {
796 32
            return [];
797 32
        }
798 3
        $attributes = [];
799
        foreach ($scenarios[$scenario] as $attribute) {
800 32
            if (strncmp($attribute, '!', 1) !== 0 && !in_array('!' . $attribute, $scenarios[$scenario])) {
801 32
                $attributes[] = $attribute;
802 32
            }
803 32
        }
804
805
        return $attributes;
806
    }
807 32
808
    /**
809
     * Returns the attribute names that are subject to validation in the current scenario.
810
     * @return string[] safe attribute names
811
     */
812
    public function activeAttributes()
813
    {
814 144
        $scenario = $this->getScenario();
815
        $scenarios = $this->scenarios();
816 144
        if (!isset($scenarios[$scenario])) {
817 144
            return [];
818 144
        }
819 3
        $attributes = array_keys(array_flip($scenarios[$scenario]));
820
        foreach ($attributes as $i => $attribute) {
821 144
            if (strncmp($attribute, '!', 1) === 0) {
822 144
                $attributes[$i] = substr($attribute, 1);
823 79
            }
824 79
        }
825
826
        return $attributes;
827
    }
828 144
829
    /**
830
     * Populates the model with input data.
831
     *
832
     * This method provides a convenient shortcut for:
833
     *
834
     * ```php
835
     * if (isset($_POST['FormName'])) {
836
     *     $model->attributes = $_POST['FormName'];
837
     *     if ($model->save()) {
838
     *         // handle success
839
     *     }
840
     * }
841
     * ```
842
     *
843
     * which, with `load()` can be written as:
844
     *
845
     * ```php
846
     * if ($model->load($_POST) && $model->save()) {
847
     *     // handle success
848
     * }
849
     * ```
850
     *
851
     * `load()` gets the `'FormName'` from the model's [[formName()]] method (which you may override), unless the
852
     * `$formName` parameter is given. If the form name is empty, `load()` populates the model with the whole of `$data`,
853
     * instead of `$data['FormName']`.
854
     *
855
     * Note, that the data being populated is subject to the safety check by [[setAttributes()]].
856
     *
857
     * @param array $data the data array to load, typically `$_POST` or `$_GET`.
858
     * @param string|null $formName the form name to use to load the data into the model, empty string when form not use.
859
     * If not set, [[formName()]] is used.
860
     * @return bool whether `load()` found the expected form in `$data`.
861
     */
862
    public function load($data, $formName = null)
863
    {
864 4
        $scope = $formName === null ? $this->formName() : $formName;
865
        if ($scope === '' && !empty($data)) {
866 4
            $this->setAttributes($data);
867 4
868 3
            return true;
869
        } elseif (isset($data[$scope])) {
870 3
            $this->setAttributes($data[$scope]);
871 3
872 2
            return true;
873
        }
874 2
875
        return false;
876
    }
877 3
878
    /**
879
     * Populates a set of models with the data from end user.
880
     * This method is mainly used to collect tabular data input.
881
     * The data to be loaded for each model is `$data[formName][index]`, where `formName`
882
     * refers to the value of [[formName()]], and `index` the index of the model in the `$models` array.
883
     * If [[formName()]] is empty, `$data[index]` will be used to populate each model.
884
     * The data being populated to each model is subject to the safety check by [[setAttributes()]].
885
     * @param array $models the models to be populated. Note that all models should have the same class.
886
     * @param array $data the data array. This is usually `$_POST` or `$_GET`, but can also be any valid array
887
     * supplied by end user.
888
     * @param string|null $formName the form name to be used for loading the data into the models.
889
     * If not set, it will use the [[formName()]] value of the first model in `$models`.
890
     * This parameter is available since version 2.0.1.
891
     * @return bool whether at least one of the models is successfully populated.
892
     */
893
    public static function loadMultiple($models, $data, $formName = null)
894
    {
895 1
        if ($formName === null) {
896
            /* @var $first Model|false */
897 1
            $first = reset($models);
898
            if ($first === false) {
899 1
                return false;
900 1
            }
901
            $formName = $first->formName();
902
        }
903 1
904
        $success = false;
905
        foreach ($models as $i => $model) {
906 1
            /* @var $model Model */
907 1
            if ($formName == '') {
908
                if (!empty($data[$i]) && $model->load($data[$i], '')) {
909 1
                    $success = true;
910 1
                }
911 1
            } elseif (!empty($data[$formName][$i]) && $model->load($data[$formName][$i], '')) {
912
                $success = true;
913 1
            }
914 1
        }
915
916
        return $success;
917
    }
918 1
919
    /**
920
     * Validates multiple models.
921
     * This method will validate every model. The models being validated may
922
     * be of the same or different types.
923
     * @param array $models the models to be validated
924
     * @param array|null $attributeNames list of attribute names that should be validated.
925
     * If this parameter is empty, it means any attribute listed in the applicable
926
     * validation rules should be validated.
927
     * @return bool whether all models are valid. False will be returned if one
928
     * or multiple models have validation error.
929
     */
930
    public static function validateMultiple($models, $attributeNames = null)
931
    {
932
        $valid = true;
933
        /* @var $model Model */
934
        foreach ($models as $model) {
935
            $valid = $model->validate($attributeNames) && $valid;
936
        }
937
938
        return $valid;
939
    }
940
941
    /**
942
     * Returns the list of fields that should be returned by default by [[toArray()]] when no specific fields are specified.
943
     *
944
     * A field is a named element in the returned array by [[toArray()]].
945
     *
946
     * This method should return an array of field names or field definitions.
947
     * If the former, the field name will be treated as an object property name whose value will be used
948
     * as the field value. If the latter, the array key should be the field name while the array value should be
949
     * the corresponding field definition which can be either an object property name or a PHP callable
950
     * returning the corresponding field value. The signature of the callable should be:
951
     *
952
     * ```php
953
     * function ($model, $field) {
954
     *     // return field value
955
     * }
956
     * ```
957
     *
958
     * For example, the following code declares four fields:
959
     *
960
     * - `email`: the field name is the same as the property name `email`;
961
     * - `firstName` and `lastName`: the field names are `firstName` and `lastName`, and their
962
     *   values are obtained from the `first_name` and `last_name` properties;
963
     * - `fullName`: the field name is `fullName`. Its value is obtained by concatenating `first_name`
964
     *   and `last_name`.
965
     *
966
     * ```php
967
     * return [
968
     *     'email',
969
     *     'firstName' => 'first_name',
970
     *     'lastName' => 'last_name',
971
     *     'fullName' => function ($model) {
972
     *         return $model->first_name . ' ' . $model->last_name;
973
     *     },
974
     * ];
975
     * ```
976
     *
977
     * In this method, you may also want to return different lists of fields based on some context
978
     * information. For example, depending on [[scenario]] or the privilege of the current application user,
979
     * you may return different sets of visible fields or filter out some fields.
980
     *
981
     * The default implementation of this method returns [[attributes()]] indexed by the same attribute names.
982
     *
983
     * @return array the list of field names or field definitions.
984
     * @see toArray()
985
     */
986
    public function fields()
987
    {
988 2
        $fields = $this->attributes();
989
990 2
        return array_combine($fields, $fields);
991
    }
992 2
993
    /**
994
     * Returns an iterator for traversing the attributes in the model.
995
     * This method is required by the interface [[\IteratorAggregate]].
996
     * @return ArrayIterator an iterator for traversing the items in the list.
997
     */
998
    #[\ReturnTypeWillChange]
999
    public function getIterator()
1000 6
    {
1001
        $attributes = $this->getAttributes();
1002 6
        return new ArrayIterator($attributes);
1003 6
    }
1004
1005
    /**
1006
     * Returns whether there is an element at the specified offset.
1007
     * This method is required by the SPL interface [[\ArrayAccess]].
1008
     * It is implicitly called when you use something like `isset($model[$offset])`.
1009
     * @param string $offset the offset to check on.
1010
     * @return bool whether or not an offset exists.
1011
     */
1012
    #[\ReturnTypeWillChange]
1013 2
    public function offsetExists($offset)
1014
    {
1015 2
        return isset($this->$offset);
1016
    }
1017
1018
    /**
1019
     * Returns the element at the specified offset.
1020
     * This method is required by the SPL interface [[\ArrayAccess]].
1021
     * It is implicitly called when you use something like `$value = $model[$offset];`.
1022
     * @param string $offset the offset to retrieve element.
1023
     * @return mixed the element at the offset, null if no element is found at the offset
1024
     */
1025 400
    #[\ReturnTypeWillChange]
1026
    public function offsetGet($offset)
1027 400
    {
1028
        return $this->$offset;
1029
    }
1030
1031
    /**
1032
     * Sets the element at the specified offset.
1033
     * This method is required by the SPL interface [[\ArrayAccess]].
1034
     * It is implicitly called when you use something like `$model[$offset] = $value;`.
1035
     * @param string $offset the offset to set element
1036
     * @param mixed $value the element value
1037 6
     */
1038
    #[\ReturnTypeWillChange]
1039 6
    public function offsetSet($offset, $value)
1040 6
    {
1041
        $this->$offset = $value;
1042
    }
1043
1044
    /**
1045
     * Sets the element value at the specified offset to null.
1046
     * This method is required by the SPL interface [[\ArrayAccess]].
1047
     * It is implicitly called when you use something like `unset($model[$offset])`.
1048 1
     * @param string $offset the offset to unset element
1049
     */
1050 1
    #[\ReturnTypeWillChange]
1051 1
    public function offsetUnset($offset)
1052
    {
1053
        $this->$offset = null;
1054
    }
1055
1056
    /**
1057
     * {@inheritdoc}
1058
     */
1059
    public function __clone()
1060
    {
1061
        parent::__clone();
1062
1063
        $this->_errors = null;
1064
        $this->_validators = null;
1065
    }
1066
}
1067