Completed
Push — master ( 9e0f19...072ef7 )
by Dmitry
10:26
created

Model::getErrorSummary()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

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

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

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