Passed
Pull Request — master (#19547)
by Fedonyuk
14:48 queued 06:07
created

Model::getIterator()   A

Complexity

Conditions 1
Paths 1

Size

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

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