Issues (836)

framework/base/Model.php (2 issues)

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

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