Issues (915)

framework/base/Model.php (2 issues)

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\base;
10
11
use ArrayAccess;
12
use ArrayIterator;
13
use ArrayObject;
14
use IteratorAggregate;
15
use ReflectionClass;
16
use Yii;
17
use yii\helpers\Inflector;
18
use yii\validators\RequiredValidator;
19
use yii\validators\Validator;
20
21
/**
22
 * Model is the base class for data models.
23
 *
24
 * Model implements the following commonly used features:
25
 *
26
 * - attribute declaration: by default, every public class member is considered as
27
 *   a model attribute
28
 * - attribute labels: each attribute may be associated with a label for display purpose
29
 * - massive attribute assignment
30
 * - scenario-based validation
31
 *
32
 * Model also raises the following events when performing data validation:
33
 *
34
 * - [[EVENT_BEFORE_VALIDATE]]: an event raised at the beginning of [[validate()]]
35
 * - [[EVENT_AFTER_VALIDATE]]: an event raised at the end of [[validate()]]
36
 *
37
 * You may directly use Model to store model data, or extend it with customization.
38
 *
39
 * For more details and usage information on Model, see the [guide article on models](guide:structure-models).
40
 *
41
 * @property-read \yii\validators\Validator[] $activeValidators The validators applicable to the current
42
 * [[scenario]].
43
 * @property array $attributes Attribute values (name => value).
44
 * @property-read array $errors Errors for all attributes or the specified attribute. Empty array is returned
45
 * if no error. See [[getErrors()]] for detailed description. Note that when returning errors for all attributes,
46
 * the result is a two-dimensional array, like the following: ```php [ 'username' => [ 'Username is required.',
47
 * 'Username must contain only word characters.', ], 'email' => [ 'Email address is invalid.', ] ] ``` .
48
 * @property-read array $firstErrors The first errors. The array keys are the attribute names, and the array
49
 * values are the corresponding error messages. An empty array will be returned if there is no error.
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 148
    public function rules()
157
    {
158 148
        return [];
159
    }
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 160
    public function scenarios()
187
    {
188 160
        $scenarios = [self::SCENARIO_DEFAULT => []];
189 160
        foreach ($this->getValidators() as $validator) {
190 84
            foreach ($validator->on as $scenario) {
191 6
                $scenarios[$scenario] = [];
192
            }
193 84
            foreach ($validator->except as $scenario) {
194 2
                $scenarios[$scenario] = [];
195
            }
196
        }
197 160
        $names = array_keys($scenarios);
198
199 160
        foreach ($this->getValidators() as $validator) {
200 84
            if (empty($validator->on) && empty($validator->except)) {
201 84
                foreach ($names as $name) {
202 84
                    foreach ($validator->attributes as $attribute) {
203 84
                        $scenarios[$name][$attribute] = true;
204
                    }
205
                }
206 6
            } elseif (empty($validator->on)) {
207 2
                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
                        }
212
                    }
213
                }
214
            } else {
215 6
                foreach ($validator->on as $name) {
216 6
                    foreach ($validator->attributes as $attribute) {
217 6
                        $scenarios[$name][$attribute] = true;
218
                    }
219
                }
220
            }
221
        }
222
223 160
        foreach ($scenarios as $scenario => $attributes) {
224 160
            if (!empty($attributes)) {
225 84
                $scenarios[$scenario] = array_keys($attributes);
226
            }
227
        }
228
229 160
        return $scenarios;
230
    }
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 97
    public function formName()
253
    {
254 97
        $reflector = new ReflectionClass($this);
255 97
        if (PHP_VERSION_ID >= 70000 && $reflector->isAnonymous()) {
256 1
            throw new InvalidConfigException('The "formName()" method should be explicitly defined for anonymous models');
257
        }
258 96
        return $reflector->getShortName();
259
    }
260
261
    /**
262
     * Returns the list of attribute names.
263
     *
264
     * By default, this method returns all public non-static properties of the class.
265
     * You may override this method to change the default behavior.
266
     *
267
     * @return string[] list of attribute names.
268
     */
269 9
    public function attributes()
270
    {
271 9
        $class = new ReflectionClass($this);
272 9
        $names = [];
273 9
        foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
274 9
            if (!$property->isStatic()) {
275 9
                $names[] = $property->getName();
276
            }
277
        }
278
279 9
        return $names;
280
    }
281
282
    /**
283
     * Returns the attribute labels.
284
     *
285
     * Attribute labels are mainly used for display purpose. For example, given an attribute
286
     * `firstName`, we can declare a label `First Name` which is more user-friendly and can
287
     * be displayed to end users.
288
     *
289
     * By default an attribute label is generated using [[generateAttributeLabel()]].
290
     * This method allows you to explicitly specify attribute labels.
291
     *
292
     * Note, in order to inherit labels defined in the parent class, a child class needs to
293
     * merge the parent labels with child labels using functions such as `array_merge()`.
294
     *
295
     * @return array attribute labels (name => label)
296
     * @see generateAttributeLabel()
297
     */
298 71
    public function attributeLabels()
299
    {
300 71
        return [];
301
    }
302
303
    /**
304
     * Returns the attribute hints.
305
     *
306
     * Attribute hints are mainly used for display purpose. For example, given an attribute
307
     * `isPublic`, we can declare a hint `Whether the post should be visible for not logged in users`,
308
     * which provides user-friendly description of the attribute meaning and can be displayed to end users.
309
     *
310
     * Unlike label hint will not be generated, if its explicit declaration is omitted.
311
     *
312
     * Note, in order to inherit hints defined in the parent class, a child class needs to
313
     * merge the parent hints with child hints using functions such as `array_merge()`.
314
     *
315
     * @return array attribute hints (name => hint)
316
     * @since 2.0.4
317
     */
318 4
    public function attributeHints()
319
    {
320 4
        return [];
321
    }
322
323
    /**
324
     * Performs the data validation.
325
     *
326
     * This method executes the validation rules applicable to the current [[scenario]].
327
     * The following criteria are used to determine whether a rule is currently applicable:
328
     *
329
     * - the rule must be associated with the attributes relevant to the current scenario;
330
     * - the rules must be effective for the current scenario.
331
     *
332
     * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
333
     * after the actual validation, respectively. If [[beforeValidate()]] returns false,
334
     * the validation will be cancelled and [[afterValidate()]] will not be called.
335
     *
336
     * Errors found during the validation can be retrieved via [[getErrors()]],
337
     * [[getFirstErrors()]] and [[getFirstError()]].
338
     *
339
     * @param string[]|string|null $attributeNames attribute name or list of attribute names
340
     * that should be validated. If this parameter is empty, it means any attribute listed in
341
     * the applicable validation rules should be validated.
342
     * @param bool $clearErrors whether to call [[clearErrors()]] before performing validation
343
     * @return bool whether the validation is successful without any error.
344
     * @throws InvalidArgumentException if the current scenario is unknown.
345
     */
346 113
    public function validate($attributeNames = null, $clearErrors = true)
347
    {
348 113
        if ($clearErrors) {
349 103
            $this->clearErrors();
350
        }
351
352 113
        if (!$this->beforeValidate()) {
353
            return false;
354
        }
355
356 113
        $scenarios = $this->scenarios();
357 113
        $scenario = $this->getScenario();
358 113
        if (!isset($scenarios[$scenario])) {
359
            throw new InvalidArgumentException("Unknown scenario: $scenario");
360
        }
361
362 113
        if ($attributeNames === null) {
363 112
            $attributeNames = $this->activeAttributes();
364
        }
365
366 113
        $attributeNames = (array)$attributeNames;
367
368 113
        foreach ($this->getActiveValidators() as $validator) {
369 62
            $validator->validateAttributes($this, $attributeNames);
370
        }
371 113
        $this->afterValidate();
372
373 113
        return !$this->hasErrors();
374
    }
375
376
    /**
377
     * This method is invoked before validation starts.
378
     * The default implementation raises a `beforeValidate` event.
379
     * You may override this method to do preliminary checks before validation.
380
     * Make sure the parent implementation is invoked so that the event can be raised.
381
     * @return bool whether the validation should be executed. Defaults to true.
382
     * If false is returned, the validation will stop and the model is considered invalid.
383
     */
384 114
    public function beforeValidate()
385
    {
386 114
        $event = new ModelEvent();
387 114
        $this->trigger(self::EVENT_BEFORE_VALIDATE, $event);
388
389 114
        return $event->isValid;
390
    }
391
392
    /**
393
     * This method is invoked after validation ends.
394
     * The default implementation raises an `afterValidate` event.
395
     * You may override this method to do postprocessing after validation.
396
     * Make sure the parent implementation is invoked so that the event can be raised.
397
     */
398 113
    public function afterValidate()
399
    {
400 113
        $this->trigger(self::EVENT_AFTER_VALIDATE);
401
    }
402
403
    /**
404
     * Returns all the validators declared in [[rules()]].
405
     *
406
     * This method differs from [[getActiveValidators()]] in that the latter
407
     * only returns the validators applicable to the current [[scenario]].
408
     *
409
     * Because this method returns an ArrayObject object, you may
410
     * manipulate it by inserting or removing validators (useful in model behaviors).
411
     * For example,
412
     *
413
     * ```php
414
     * $model->validators[] = $newValidator;
415
     * ```
416
     *
417
     * @return ArrayObject|\yii\validators\Validator[] all the validators declared in the model.
418
     */
419 178
    public function getValidators()
420
    {
421 178
        if ($this->_validators === null) {
422 178
            $this->_validators = $this->createValidators();
423
        }
424
425 178
        return $this->_validators;
426
    }
427
428
    /**
429
     * Returns the validators applicable to the current [[scenario]].
430
     * @param string|null $attribute the name of the attribute whose applicable validators should be returned.
431
     * If this is null, the validators for ALL attributes in the model will be returned.
432
     * @return \yii\validators\Validator[] the validators applicable to the current [[scenario]].
433
     */
434 154
    public function getActiveValidators($attribute = null)
435
    {
436 154
        $activeAttributes = $this->activeAttributes();
437 154
        if ($attribute !== null && !in_array($attribute, $activeAttributes, true)) {
438 26
            return [];
439
        }
440 130
        $scenario = $this->getScenario();
441 130
        $validators = [];
442 130
        foreach ($this->getValidators() as $validator) {
443 79
            if ($attribute === null) {
444 63
                $validatorAttributes = $validator->getValidationAttributes($activeAttributes);
445 63
                $attributeValid = !empty($validatorAttributes);
446
            } else {
447 17
                $attributeValid = in_array($attribute, $validator->getValidationAttributes($attribute), true);
448
            }
449 79
            if ($attributeValid && $validator->isActive($scenario)) {
450 79
                $validators[] = $validator;
451
            }
452
        }
453
454 130
        return $validators;
455
    }
456
457
    /**
458
     * Creates validator objects based on the validation rules specified in [[rules()]].
459
     * Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned.
460
     * @return ArrayObject validators
461
     * @throws InvalidConfigException if any validation rule configuration is invalid
462
     */
463 179
    public function createValidators()
464
    {
465 179
        $validators = new ArrayObject();
466 179
        foreach ($this->rules() as $rule) {
467 61
            if ($rule instanceof Validator) {
468
                $validators->append($rule);
469 61
            } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
470 60
                $validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2));
471 60
                $validators->append($validator);
472
            } else {
473 1
                throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
474
            }
475
        }
476
477 178
        return $validators;
478
    }
479
480
    /**
481
     * Returns a value indicating whether the attribute is required.
482
     * This is determined by checking if the attribute is associated with a
483
     * [[\yii\validators\RequiredValidator|required]] validation rule in the
484
     * current [[scenario]].
485
     *
486
     * Note that when the validator has a conditional validation applied using
487
     * [[\yii\validators\RequiredValidator::$when|$when]] this method will return
488
     * `false` regardless of the `when` condition because it may be called be
489
     * before the model is loaded with data.
490
     *
491
     * @param string $attribute attribute name
492
     * @return bool whether the attribute is required
493
     */
494 30
    public function isAttributeRequired($attribute)
495
    {
496 30
        foreach ($this->getActiveValidators($attribute) as $validator) {
497 6
            if ($validator instanceof RequiredValidator && $validator->when === null) {
498 5
                return true;
499
            }
500
        }
501
502 26
        return false;
503
    }
504
505
    /**
506
     * Returns a value indicating whether the attribute is safe for massive assignments.
507
     * @param string $attribute attribute name
508
     * @return bool whether the attribute is safe for massive assignments
509
     * @see safeAttributes()
510
     */
511 24
    public function isAttributeSafe($attribute)
512
    {
513 24
        return in_array($attribute, $this->safeAttributes(), true);
514
    }
515
516
    /**
517
     * Returns a value indicating whether the attribute is active in the current scenario.
518
     * @param string $attribute attribute name
519
     * @return bool whether the attribute is active in the current scenario
520
     * @see activeAttributes()
521
     */
522 4
    public function isAttributeActive($attribute)
523
    {
524 4
        return in_array($attribute, $this->activeAttributes(), true);
525
    }
526
527
    /**
528
     * Returns the text label for the specified attribute.
529
     * @param string $attribute the attribute name
530
     * @return string the attribute label
531
     * @see generateAttributeLabel()
532
     * @see attributeLabels()
533
     */
534 52
    public function getAttributeLabel($attribute)
535
    {
536 52
        $labels = $this->attributeLabels();
537 52
        return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
538
    }
539
540
    /**
541
     * Returns the text hint for the specified attribute.
542
     * @param string $attribute the attribute name
543
     * @return string the attribute hint
544
     * @see attributeHints()
545
     * @since 2.0.4
546
     */
547 16
    public function getAttributeHint($attribute)
548
    {
549 16
        $hints = $this->attributeHints();
550 16
        return isset($hints[$attribute]) ? $hints[$attribute] : '';
551
    }
552
553
    /**
554
     * Returns a value indicating whether there is any validation error.
555
     * @param string|null $attribute attribute name. Use null to check all attributes.
556
     * @return bool whether there is any error.
557
     */
558 432
    public function hasErrors($attribute = null)
559
    {
560 432
        return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
561
    }
562
563
    /**
564
     * Returns the errors for all attributes or a single attribute.
565
     * @param string|null $attribute attribute name. Use null to retrieve errors for all attributes.
566
     * @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
567
     * See [[getErrors()]] for detailed description.
568
     * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
569
     *
570
     * ```php
571
     * [
572
     *     'username' => [
573
     *         'Username is required.',
574
     *         'Username must contain only word characters.',
575
     *     ],
576
     *     'email' => [
577
     *         'Email address is invalid.',
578
     *     ]
579
     * ]
580
     * ```
581
     *
582
     * @see getFirstErrors()
583
     * @see getFirstError()
584
     */
585 49
    public function getErrors($attribute = null)
586
    {
587 49
        if ($attribute === null) {
588 9
            return $this->_errors === null ? [] : $this->_errors;
589
        }
590
591 41
        return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
592
    }
593
594
    /**
595
     * Returns the first error of every attribute in the model.
596
     * @return array the first errors. The array keys are the attribute names, and the array
597
     * values are the corresponding error messages. An empty array will be returned if there is no error.
598
     * @see getErrors()
599
     * @see getFirstError()
600
     */
601 9
    public function getFirstErrors()
602
    {
603 9
        if (empty($this->_errors)) {
604 4
            return [];
605
        }
606
607 6
        $errors = [];
608 6
        foreach ($this->_errors as $name => $es) {
609 6
            if (!empty($es)) {
610 6
                $errors[$name] = reset($es);
611
            }
612
        }
613
614 6
        return $errors;
615
    }
616
617
    /**
618
     * Returns the first error of the specified attribute.
619
     * @param string $attribute attribute name.
620
     * @return string|null the error message. Null is returned if no error.
621
     * @see getErrors()
622
     * @see getFirstErrors()
623
     */
624 42
    public function getFirstError($attribute)
625
    {
626 42
        return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
627
    }
628
629
    /**
630
     * Returns the errors for all attributes as a one-dimensional array.
631
     * @param bool $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
632
     * only the first error message for each attribute will be shown.
633
     * @return array errors for all attributes as a one-dimensional array. Empty array is returned if no error.
634
     * @see getErrors()
635
     * @see getFirstErrors()
636
     * @since 2.0.14
637
     */
638 12
    public function getErrorSummary($showAllErrors)
639
    {
640 12
        $lines = [];
641 12
        $errors = $showAllErrors ? $this->getErrors() : $this->getFirstErrors();
642 12
        foreach ($errors as $es) {
643 9
            $lines = array_merge($lines, (array)$es);
644
        }
645 12
        return $lines;
646
    }
647
648
    /**
649
     * Adds a new error to the specified attribute.
650
     * @param string $attribute attribute name
651
     * @param string $error new error message
652
     */
653 154
    public function addError($attribute, $error = '')
654
    {
655 154
        $this->_errors[$attribute][] = $error;
656
    }
657
658
    /**
659
     * Adds a list of errors.
660
     * @param array $items a list of errors. The array keys must be attribute names.
661
     * The array values should be error messages. If an attribute has multiple errors,
662
     * these errors must be given in terms of an array.
663
     * You may use the result of [[getErrors()]] as the value for this parameter.
664
     * @since 2.0.2
665
     */
666 7
    public function addErrors(array $items)
667
    {
668 7
        foreach ($items as $attribute => $errors) {
669 7
            if (is_array($errors)) {
670 7
                foreach ($errors as $error) {
671 7
                    $this->addError($attribute, $error);
672
                }
673
            } else {
674 1
                $this->addError($attribute, $errors);
675
            }
676
        }
677
    }
678
679
    /**
680
     * Removes errors for all attributes or a single attribute.
681
     * @param string|null $attribute attribute name. Use null to remove errors for all attributes.
682
     */
683 135
    public function clearErrors($attribute = null)
684
    {
685 135
        if ($attribute === null) {
686 131
            $this->_errors = [];
687
        } else {
688 5
            unset($this->_errors[$attribute]);
689
        }
690
    }
691
692
    /**
693
     * Generates a user friendly attribute label based on the give attribute name.
694
     * This is done by replacing underscores, dashes and dots with blanks and
695
     * changing the first letter of each word to upper case.
696
     * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
697
     * @param string $name the column name
698
     * @return string the attribute label
699
     */
700 105
    public function generateAttributeLabel($name)
701
    {
702 105
        return Inflector::camel2words($name, true);
703
    }
704
705
    /**
706
     * Returns attribute values.
707
     * @param array|null $names list of attributes whose value needs to be returned.
708
     * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
709
     * If it is an array, only the attributes in the array will be returned.
710
     * @param array $except list of attributes whose value should NOT be returned.
711
     * @return array attribute values (name => value).
712
     */
713 17
    public function getAttributes($names = null, $except = [])
714
    {
715 17
        $values = [];
716 17
        if ($names === null) {
717 17
            $names = $this->attributes();
718
        }
719 17
        foreach ($names as $name) {
720 17
            $values[$name] = $this->$name;
721
        }
722 17
        foreach ($except as $name) {
723 1
            unset($values[$name]);
724
        }
725
726 17
        return $values;
727
    }
728
729
    /**
730
     * Sets the attribute values in a massive way.
731
     * @param array $values attribute values (name => value) to be assigned to the model.
732
     * @param bool $safeOnly whether the assignments should only be done to the safe attributes.
733
     * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
734
     * @see safeAttributes()
735
     * @see attributes()
736
     */
737 14
    public function setAttributes($values, $safeOnly = true)
738
    {
739 14
        if (is_array($values)) {
0 ignored issues
show
The condition is_array($values) is always true.
Loading history...
740 14
            $attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
741 14
            foreach ($values as $name => $value) {
742 14
                if (isset($attributes[$name])) {
743 14
                    $this->$name = $value;
744 3
                } elseif ($safeOnly) {
745 3
                    $this->onUnsafeAttribute($name, $value);
746
                }
747
            }
748
        }
749
    }
750
751
    /**
752
     * This method is invoked when an unsafe attribute is being massively assigned.
753
     * The default implementation will log a warning message if YII_DEBUG is on.
754
     * It does nothing otherwise.
755
     * @param string $name the unsafe attribute name
756
     * @param mixed $value the attribute value
757
     */
758 3
    public function onUnsafeAttribute($name, $value)
0 ignored issues
show
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

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