Completed
Push — fix-error-handling-regression ( ef2bf2 )
by Alexander
09:24
created

Model::offsetSet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
cc 1
eloc 2
nc 1
nop 2
crap 1
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 IteratorAggregate, ArrayAccess, Arrayable
58
{
59
    use ArrayableTrait;
60
61
    /**
62
     * The name of the default scenario.
63
     */
64
    const SCENARIO_DEFAULT = 'default';
65
    /**
66
     * @event ModelEvent an event raised at the beginning of [[validate()]]. You may set
67
     * [[ModelEvent::isValid]] to be false to stop the validation.
68
     */
69
    const EVENT_BEFORE_VALIDATE = 'beforeValidate';
70
    /**
71
     * @event Event an event raised at the end of [[validate()]]
72
     */
73
    const EVENT_AFTER_VALIDATE = 'afterValidate';
74
75
    /**
76
     * @var array validation errors (attribute name => array of errors)
77
     */
78
    private $_errors;
79
    /**
80
     * @var ArrayObject list of validators
81
     */
82
    private $_validators;
83
    /**
84
     * @var string current scenario
85
     */
86
    private $_scenario = self::SCENARIO_DEFAULT;
87
88
89
    /**
90
     * Returns the validation rules for attributes.
91
     *
92
     * Validation rules are used by [[validate()]] to check if attribute values are valid.
93
     * Child classes may override this method to declare different validation rules.
94
     *
95
     * Each rule is an array with the following structure:
96
     *
97
     * ```php
98
     * [
99
     *     ['attribute1', 'attribute2'],
100
     *     'validator type',
101
     *     'on' => ['scenario1', 'scenario2'],
102
     *     //...other parameters...
103
     * ]
104
     * ```
105
     *
106
     * where
107
     *
108
     *  - attribute list: required, specifies the attributes array to be validated, for single attribute you can pass a string;
109
     *  - validator type: required, specifies the validator to be used. It can be a built-in validator name,
110
     *    a method name of the model class, an anonymous function, or a validator class name.
111
     *  - on: optional, specifies the [[scenario|scenarios]] array in which the validation
112
     *    rule can be applied. If this option is not set, the rule will apply to all scenarios.
113
     *  - additional name-value pairs can be specified to initialize the corresponding validator properties.
114
     *    Please refer to individual validator class API for possible properties.
115
     *
116
     * A validator can be either an object of a class extending [[Validator]], or a model class method
117
     * (called *inline validator*) that has the following signature:
118
     *
119
     * ```php
120
     * // $params refers to validation parameters given in the rule
121
     * function validatorName($attribute, $params)
122
     * ```
123
     *
124
     * In the above `$attribute` refers to the attribute currently being validated while `$params` contains an array of
125
     * validator configuration options such as `max` in case of `string` validator. The value of the attribute currently being validated
126
     * can be accessed as `$this->$attribute`. Note the `$` before `attribute`; this is taking the value of the variable
127
     * `$attribute` and using it as the name of the property to access.
128
     *
129
     * Yii also provides a set of [[Validator::builtInValidators|built-in validators]].
130
     * Each one has an alias name which can be used when specifying a validation rule.
131
     *
132
     * Below are some examples:
133
     *
134
     * ```php
135
     * [
136
     *     // built-in "required" validator
137
     *     [['username', 'password'], 'required'],
138
     *     // built-in "string" validator customized with "min" and "max" properties
139
     *     ['username', 'string', 'min' => 3, 'max' => 12],
140
     *     // built-in "compare" validator that is used in "register" scenario only
141
     *     ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
142
     *     // an inline validator defined via the "authenticate()" method in the model class
143
     *     ['password', 'authenticate', 'on' => 'login'],
144
     *     // a validator of class "DateRangeValidator"
145
     *     ['dateRange', 'DateRangeValidator'],
146
     * ];
147
     * ```
148
     *
149
     * Note, in order to inherit rules defined in the parent class, a child class needs to
150
     * merge the parent rules with child rules using functions such as `array_merge()`.
151
     *
152
     * @return array validation rules
153
     * @see scenarios()
154
     */
155 54
    public function rules()
156
    {
157 54
        return [];
158
    }
159
160
    /**
161
     * Returns a list of scenarios and the corresponding active attributes.
162
     * An active attribute is one that is subject to validation in the current scenario.
163
     * The returned array should be in the following format:
164
     *
165
     * ```php
166
     * [
167
     *     'scenario1' => ['attribute11', 'attribute12', ...],
168
     *     'scenario2' => ['attribute21', 'attribute22', ...],
169
     *     ...
170
     * ]
171
     * ```
172
     *
173
     * By default, an active attribute is considered safe and can be massively assigned.
174
     * If an attribute should NOT be massively assigned (thus considered unsafe),
175
     * please prefix the attribute with an exclamation character (e.g. `'!rank'`).
176
     *
177
     * The default implementation of this method will return all scenarios found in the [[rules()]]
178
     * declaration. A special scenario named [[SCENARIO_DEFAULT]] will contain all attributes
179
     * found in the [[rules()]]. Each scenario will be associated with the attributes that
180
     * are being validated by the validation rules that apply to the scenario.
181
     *
182
     * @return array a list of scenarios and the corresponding active attributes.
183
     */
184 44
    public function scenarios()
185
    {
186 44
        $scenarios = [self::SCENARIO_DEFAULT => []];
187 44
        foreach ($this->getValidators() as $validator) {
188 20
            foreach ($validator->on as $scenario) {
189 4
                $scenarios[$scenario] = [];
190
            }
191 20
            foreach ($validator->except as $scenario) {
192 20
                $scenarios[$scenario] = [];
193
            }
194
        }
195 44
        $names = array_keys($scenarios);
196
197 44
        foreach ($this->getValidators() as $validator) {
198 20
            if (empty($validator->on) && empty($validator->except)) {
199 20
                foreach ($names as $name) {
200 20
                    foreach ($validator->attributes as $attribute) {
201 20
                        $scenarios[$name][$attribute] = true;
202
                    }
203
                }
204 4
            } elseif (empty($validator->on)) {
205 1
                foreach ($names as $name) {
206 1
                    if (!in_array($name, $validator->except, true)) {
207 1
                        foreach ($validator->attributes as $attribute) {
208 1
                            $scenarios[$name][$attribute] = true;
209
                        }
210
                    }
211
                }
212
            } else {
213 4
                foreach ($validator->on as $name) {
214 4
                    foreach ($validator->attributes as $attribute) {
215 4
                        $scenarios[$name][$attribute] = true;
216
                    }
217
                }
218
            }
219
        }
220
221 44
        foreach ($scenarios as $scenario => $attributes) {
222 44
            if (!empty($attributes)) {
223 20
                $scenarios[$scenario] = array_keys($attributes);
224
            }
225
        }
226
227 44
        return $scenarios;
228
    }
229
230
    /**
231
     * Returns the form name that this model class should use.
232
     *
233
     * The form name is mainly used by [[\yii\widgets\ActiveForm]] to determine how to name
234
     * the input fields for the attributes in a model. If the form name is "A" and an attribute
235
     * name is "b", then the corresponding input name would be "A[b]". If the form name is
236
     * an empty string, then the input name would be "b".
237
     *
238
     * The purpose of the above naming schema is that for forms which contain multiple different models,
239
     * the attributes of each model are grouped in sub-arrays of the POST-data and it is easier to
240
     * differentiate between them.
241
     *
242
     * By default, this method returns the model class name (without the namespace part)
243
     * as the form name. You may override it when the model is used in different forms.
244
     *
245
     * @return string the form name of this model class.
246
     * @see load()
247
     */
248 54
    public function formName()
249
    {
250 54
        $reflector = new ReflectionClass($this);
251 54
        return $reflector->getShortName();
252
    }
253
254
    /**
255
     * Returns the list of attribute names.
256
     * By default, this method returns all public non-static properties of the class.
257
     * You may override this method to change the default behavior.
258
     * @return array list of attribute names.
259
     */
260 4
    public function attributes()
261
    {
262 4
        $class = new ReflectionClass($this);
263 4
        $names = [];
264 4
        foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
265 4
            if (!$property->isStatic()) {
266 4
                $names[] = $property->getName();
267
            }
268
        }
269
270 4
        return $names;
271
    }
272
273
    /**
274
     * Returns the attribute labels.
275
     *
276
     * Attribute labels are mainly used for display purpose. For example, given an attribute
277
     * `firstName`, we can declare a label `First Name` which is more user-friendly and can
278
     * be displayed to end users.
279
     *
280
     * By default an attribute label is generated using [[generateAttributeLabel()]].
281
     * This method allows you to explicitly specify attribute labels.
282
     *
283
     * Note, in order to inherit labels defined in the parent class, a child class needs to
284
     * merge the parent labels with child labels using functions such as `array_merge()`.
285
     *
286
     * @return array attribute labels (name => label)
287
     * @see generateAttributeLabel()
288
     */
289 66
    public function attributeLabels()
290
    {
291 66
        return [];
292
    }
293
294
    /**
295
     * Returns the attribute hints.
296
     *
297
     * Attribute hints are mainly used for display purpose. For example, given an attribute
298
     * `isPublic`, we can declare a hint `Whether the post should be visible for not logged in users`,
299
     * which provides user-friendly description of the attribute meaning and can be displayed to end users.
300
     *
301
     * Unlike label hint will not be generated, if its explicit declaration is omitted.
302
     *
303
     * Note, in order to inherit hints defined in the parent class, a child class needs to
304
     * merge the parent hints with child hints using functions such as `array_merge()`.
305
     *
306
     * @return array attribute hints (name => hint)
307
     * @since 2.0.4
308
     */
309 3
    public function attributeHints()
310
    {
311 3
        return [];
312
    }
313
314
    /**
315
     * Performs the data validation.
316
     *
317
     * This method executes the validation rules applicable to the current [[scenario]].
318
     * The following criteria are used to determine whether a rule is currently applicable:
319
     *
320
     * - the rule must be associated with the attributes relevant to the current scenario;
321
     * - the rules must be effective for the current scenario.
322
     *
323
     * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
324
     * after the actual validation, respectively. If [[beforeValidate()]] returns false,
325
     * the validation will be cancelled and [[afterValidate()]] will not be called.
326
     *
327
     * Errors found during the validation can be retrieved via [[getErrors()]],
328
     * [[getFirstErrors()]] and [[getFirstError()]].
329
     *
330
     * @param array $attributeNames list of attribute names that should be validated.
331
     * If this parameter is empty, it means any attribute listed in the applicable
332
     * validation rules should be validated.
333
     * @param bool $clearErrors whether to call [[clearErrors()]] before performing validation
334
     * @return bool whether the validation is successful without any error.
335
     * @throws InvalidParamException if the current scenario is unknown.
336
     */
337 37
    public function validate($attributeNames = null, $clearErrors = true)
338
    {
339 37
        if ($clearErrors) {
340 30
            $this->clearErrors();
341
        }
342
343 37
        if (!$this->beforeValidate()) {
344
            return false;
345
        }
346
347 37
        $scenarios = $this->scenarios();
348 37
        $scenario = $this->getScenario();
349 37
        if (!isset($scenarios[$scenario])) {
350
            throw new InvalidParamException("Unknown scenario: $scenario");
351
        }
352
353 37
        if ($attributeNames === null) {
354 37
            $attributeNames = $this->activeAttributes();
355
        }
356
357 37
        foreach ($this->getActiveValidators() as $validator) {
358 14
            $validator->validateAttributes($this, $attributeNames);
359
        }
360 37
        $this->afterValidate();
361
362 37
        return !$this->hasErrors();
363
    }
364
365
    /**
366
     * This method is invoked before validation starts.
367
     * The default implementation raises a `beforeValidate` event.
368
     * You may override this method to do preliminary checks before validation.
369
     * Make sure the parent implementation is invoked so that the event can be raised.
370
     * @return bool whether the validation should be executed. Defaults to true.
371
     * If false is returned, the validation will stop and the model is considered invalid.
372
     */
373 38
    public function beforeValidate()
374
    {
375 38
        $event = new ModelEvent();
376 38
        $this->trigger(self::EVENT_BEFORE_VALIDATE, $event);
377
378 38
        return $event->isValid;
379
    }
380
381
    /**
382
     * This method is invoked after validation ends.
383
     * The default implementation raises an `afterValidate` event.
384
     * You may override this method to do postprocessing after validation.
385
     * Make sure the parent implementation is invoked so that the event can be raised.
386
     */
387 37
    public function afterValidate()
388
    {
389 37
        $this->trigger(self::EVENT_AFTER_VALIDATE);
390 37
    }
391
392
    /**
393
     * Returns all the validators declared in [[rules()]].
394
     *
395
     * This method differs from [[getActiveValidators()]] in that the latter
396
     * only returns the validators applicable to the current [[scenario]].
397
     *
398
     * Because this method returns an ArrayObject object, you may
399
     * manipulate it by inserting or removing validators (useful in model behaviors).
400
     * For example,
401
     *
402
     * ```php
403
     * $model->validators[] = $newValidator;
404
     * ```
405
     *
406
     * @return ArrayObject|\yii\validators\Validator[] all the validators declared in the model.
407
     */
408 71
    public function getValidators()
409
    {
410 71
        if ($this->_validators === null) {
411 71
            $this->_validators = $this->createValidators();
412
        }
413 71
        return $this->_validators;
414
    }
415
416
    /**
417
     * Returns the validators applicable to the current [[scenario]].
418
     * @param string $attribute the name of the attribute whose applicable validators should be returned.
419
     * If this is null, the validators for ALL attributes in the model will be returned.
420
     * @return \yii\validators\Validator[] the validators applicable to the current [[scenario]].
421
     */
422 64
    public function getActiveValidators($attribute = null)
423
    {
424 64
        $validators = [];
425 64
        $scenario = $this->getScenario();
426 64
        foreach ($this->getValidators() as $validator) {
427 25
            if ($validator->isActive($scenario) && ($attribute === null || in_array($attribute, $validator->getAttributeNames(), true))) {
428 25
                $validators[] = $validator;
429
            }
430
        }
431 64
        return $validators;
432
    }
433
434
    /**
435
     * Creates validator objects based on the validation rules specified in [[rules()]].
436
     * Unlike [[getValidators()]], each time this method is called, a new list of validators will be returned.
437
     * @return ArrayObject validators
438
     * @throws InvalidConfigException if any validation rule configuration is invalid
439
     */
440 72
    public function createValidators()
441
    {
442 72
        $validators = new ArrayObject();
443 72
        foreach ($this->rules() as $rule) {
444 19
            if ($rule instanceof Validator) {
445
                $validators->append($rule);
446 19
            } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
447 18
                $validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2));
448 18
                $validators->append($validator);
449
            } else {
450 1
                throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
451
            }
452
        }
453 71
        return $validators;
454
    }
455
456
    /**
457
     * Returns a value indicating whether the attribute is required.
458
     * This is determined by checking if the attribute is associated with a
459
     * [[\yii\validators\RequiredValidator|required]] validation rule in the
460
     * current [[scenario]].
461
     *
462
     * Note that when the validator has a conditional validation applied using
463
     * [[\yii\validators\RequiredValidator::$when|$when]] this method will return
464
     * `false` regardless of the `when` condition because it may be called be
465
     * before the model is loaded with data.
466
     *
467
     * @param string $attribute attribute name
468
     * @return bool whether the attribute is required
469
     */
470 21
    public function isAttributeRequired($attribute)
471
    {
472 21
        foreach ($this->getActiveValidators($attribute) as $validator) {
473 5
            if ($validator instanceof RequiredValidator && $validator->when === null) {
474 4
                return true;
475
            }
476
        }
477 18
        return false;
478
    }
479
480
    /**
481
     * Returns a value indicating whether the attribute is safe for massive assignments.
482
     * @param string $attribute attribute name
483
     * @return bool whether the attribute is safe for massive assignments
484
     * @see safeAttributes()
485
     */
486 1
    public function isAttributeSafe($attribute)
487
    {
488 1
        return in_array($attribute, $this->safeAttributes(), true);
489
    }
490
491
    /**
492
     * Returns a value indicating whether the attribute is active in the current scenario.
493
     * @param string $attribute attribute name
494
     * @return bool whether the attribute is active in the current scenario
495
     * @see activeAttributes()
496
     */
497 2
    public function isAttributeActive($attribute)
498
    {
499 2
        return in_array($attribute, $this->activeAttributes(), true);
500
    }
501
502
    /**
503
     * Returns the text label for the specified attribute.
504
     * @param string $attribute the attribute name
505
     * @return string the attribute label
506
     * @see generateAttributeLabel()
507
     * @see attributeLabels()
508
     */
509 25
    public function getAttributeLabel($attribute)
510
    {
511 25
        $labels = $this->attributeLabels();
512 25
        return isset($labels[$attribute]) ? $labels[$attribute] : $this->generateAttributeLabel($attribute);
513
    }
514
515
    /**
516
     * Returns the text hint for the specified attribute.
517
     * @param string $attribute the attribute name
518
     * @return string the attribute hint
519
     * @see attributeHints()
520
     * @since 2.0.4
521
     */
522 10
    public function getAttributeHint($attribute)
523
    {
524 10
        $hints = $this->attributeHints();
525 10
        return isset($hints[$attribute]) ? $hints[$attribute] : '';
526
    }
527
528
    /**
529
     * Returns a value indicating whether there is any validation error.
530
     * @param string|null $attribute attribute name. Use null to check all attributes.
531
     * @return bool whether there is any error.
532
     */
533 275
    public function hasErrors($attribute = null)
534
    {
535 275
        return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
536
    }
537
538
    /**
539
     * Returns the errors for all attributes or a single attribute.
540
     * @param string $attribute attribute name. Use null to retrieve errors for all attributes.
541
     * @property array An array of errors for all attributes. Empty array is returned if no error.
542
     * The result is a two-dimensional array. See [[getErrors()]] for detailed description.
543
     * @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
544
     * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
545
     *
546
     * ```php
547
     * [
548
     *     'username' => [
549
     *         'Username is required.',
550
     *         'Username must contain only word characters.',
551
     *     ],
552
     *     'email' => [
553
     *         'Email address is invalid.',
554
     *     ]
555
     * ]
556
     * ```
557
     *
558
     * @see getFirstErrors()
559
     * @see getFirstError()
560
     */
561 28
    public function getErrors($attribute = null)
562
    {
563 28
        if ($attribute === null) {
564 9
            return $this->_errors === null ? [] : $this->_errors;
565
        }
566 20
        return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
567
    }
568
569
    /**
570
     * Returns the first error of every attribute in the model.
571
     * @return array the first errors. The array keys are the attribute names, and the array
572
     * values are the corresponding error messages. An empty array will be returned if there is no error.
573
     * @see getErrors()
574
     * @see getFirstError()
575
     */
576 2
    public function getFirstErrors()
577
    {
578 2
        if (empty($this->_errors)) {
579 1
            return [];
580
        }
581
582 2
        $errors = [];
583 2
        foreach ($this->_errors as $name => $es) {
584 2
            if (!empty($es)) {
585 2
                $errors[$name] = reset($es);
586
            }
587
        }
588 2
        return $errors;
589
    }
590
591
    /**
592
     * Returns the first error of the specified attribute.
593
     * @param string $attribute attribute name.
594
     * @return string the error message. Null is returned if no error.
595
     * @see getErrors()
596
     * @see getFirstErrors()
597
     */
598 29
    public function getFirstError($attribute)
599
    {
600 29
        return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
601
    }
602
603
    /**
604
     * Adds a new error to the specified attribute.
605
     * @param string $attribute attribute name
606
     * @param string $error new error message
607
     */
608 102
    public function addError($attribute, $error = '')
609
    {
610 102
        $this->_errors[$attribute][] = $error;
611 102
    }
612
613
    /**
614
     * Adds a list of errors.
615
     * @param array $items a list of errors. The array keys must be attribute names.
616
     * The array values should be error messages. If an attribute has multiple errors,
617
     * these errors must be given in terms of an array.
618
     * You may use the result of [[getErrors()]] as the value for this parameter.
619
     * @since 2.0.2
620
     */
621 7
    public function addErrors(array $items)
622
    {
623 7
        foreach ($items as $attribute => $errors) {
624 7
            if (is_array($errors)) {
625 7
                foreach ($errors as $error) {
626 7
                    $this->addError($attribute, $error);
627
                }
628
            } else {
629 1
                $this->addError($attribute, $errors);
630
            }
631
        }
632 7
    }
633
634
    /**
635
     * Removes errors for all attributes or a single attribute.
636
     * @param string $attribute attribute name. Use null to remove errors for all attributes.
637
     */
638 62
    public function clearErrors($attribute = null)
639
    {
640 62
        if ($attribute === null) {
641 56
            $this->_errors = [];
642
        } else {
643 11
            unset($this->_errors[$attribute]);
644
        }
645 62
    }
646
647
    /**
648
     * Generates a user friendly attribute label based on the give attribute name.
649
     * This is done by replacing underscores, dashes and dots with blanks and
650
     * changing the first letter of each word to upper case.
651
     * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
652
     * @param string $name the column name
653
     * @return string the attribute label
654
     */
655 73
    public function generateAttributeLabel($name)
656
    {
657 73
        return Inflector::camel2words($name, true);
658
    }
659
660
    /**
661
     * Returns attribute values.
662
     * @param array $names list of attributes whose value needs to be returned.
663
     * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
664
     * If it is an array, only the attributes in the array will be returned.
665
     * @param array $except list of attributes whose value should NOT be returned.
666
     * @return array attribute values (name => value).
667
     */
668 5
    public function getAttributes($names = null, $except = [])
669
    {
670 5
        $values = [];
671 5
        if ($names === null) {
672 5
            $names = $this->attributes();
673
        }
674 5
        foreach ($names as $name) {
675 5
            $values[$name] = $this->$name;
676
        }
677 5
        foreach ($except as $name) {
678 1
            unset($values[$name]);
679
        }
680
681 5
        return $values;
682
    }
683
684
    /**
685
     * Sets the attribute values in a massive way.
686
     * @param array $values attribute values (name => value) to be assigned to the model.
687
     * @param bool $safeOnly whether the assignments should only be done to the safe attributes.
688
     * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
689
     * @see safeAttributes()
690
     * @see attributes()
691
     */
692 13
    public function setAttributes($values, $safeOnly = true)
693
    {
694 13
        if (is_array($values)) {
695 13
            $attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
696 13
            foreach ($values as $name => $value) {
697 13
                if (isset($attributes[$name])) {
698 13
                    $this->$name = $value;
699 2
                } elseif ($safeOnly) {
700 2
                    $this->onUnsafeAttribute($name, $value);
701
                }
702
            }
703
        }
704 13
    }
705
706
    /**
707
     * This method is invoked when an unsafe attribute is being massively assigned.
708
     * The default implementation will log a warning message if YII_DEBUG is on.
709
     * It does nothing otherwise.
710
     * @param string $name the unsafe attribute name
711
     * @param mixed $value the attribute value
712
     */
713 2
    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...
714
    {
715 2
        if (YII_DEBUG) {
716 2
            Yii::trace("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.", __METHOD__);
717
        }
718 2
    }
719
720
    /**
721
     * Returns the scenario that this model is used in.
722
     *
723
     * Scenario affects how validation is performed and which attributes can
724
     * be massively assigned.
725
     *
726
     * @return string the scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
727
     */
728 150
    public function getScenario()
729
    {
730 150
        return $this->_scenario;
731
    }
732
733
    /**
734
     * Sets the scenario for the model.
735
     * Note that this method does not check if the scenario exists or not.
736
     * The method [[validate()]] will perform this check.
737
     * @param string $value the scenario that this model is in.
738
     */
739 8
    public function setScenario($value)
740
    {
741 8
        $this->_scenario = $value;
742 8
    }
743
744
    /**
745
     * Returns the attribute names that are safe to be massively assigned in the current scenario.
746
     * @return string[] safe attribute names
747
     */
748 8
    public function safeAttributes()
749
    {
750 8
        $scenario = $this->getScenario();
751 8
        $scenarios = $this->scenarios();
752 8
        if (!isset($scenarios[$scenario])) {
753 3
            return [];
754
        }
755 8
        $attributes = [];
756 8
        foreach ($scenarios[$scenario] as $attribute) {
757 8
            if ($attribute[0] !== '!' && !in_array('!' . $attribute, $scenarios[$scenario])) {
758 8
                $attributes[] = $attribute;
759
            }
760
        }
761
762 8
        return $attributes;
763
    }
764
765
    /**
766
     * Returns the attribute names that are subject to validation in the current scenario.
767
     * @return string[] safe attribute names
768
     */
769 44
    public function activeAttributes()
770
    {
771 44
        $scenario = $this->getScenario();
772 44
        $scenarios = $this->scenarios();
773 44
        if (!isset($scenarios[$scenario])) {
774 2
            return [];
775
        }
776 44
        $attributes = $scenarios[$scenario];
777 44
        foreach ($attributes as $i => $attribute) {
778 20
            if ($attribute[0] === '!') {
779 3
                $attributes[$i] = substr($attribute, 1);
780
            }
781
        }
782
783 44
        return $attributes;
784
    }
785
786
    /**
787
     * Populates the model with input data.
788
     *
789
     * This method provides a convenient shortcut for:
790
     *
791
     * ```php
792
     * if (isset($_POST['FormName'])) {
793
     *     $model->attributes = $_POST['FormName'];
794
     *     if ($model->save()) {
795
     *         // handle success
796
     *     }
797
     * }
798
     * ```
799
     *
800
     * which, with `load()` can be written as:
801
     *
802
     * ```php
803
     * if ($model->load($_POST) && $model->save()) {
804
     *     // handle success
805
     * }
806
     * ```
807
     *
808
     * `load()` gets the `'FormName'` from the model's [[formName()]] method (which you may override), unless the
809
     * `$formName` parameter is given. If the form name is empty, `load()` populates the model with the whole of `$data`,
810
     * instead of `$data['FormName']`.
811
     *
812
     * Note, that the data being populated is subject to the safety check by [[setAttributes()]].
813
     *
814
     * @param array $data the data array to load, typically `$_POST` or `$_GET`.
815
     * @param string $formName the form name to use to load the data into the model.
816
     * If not set, [[formName()]] is used.
817
     * @return bool whether `load()` found the expected form in `$data`.
818
     */
819 3
    public function load($data, $formName = null)
820
    {
821 3
        $scope = $formName === null ? $this->formName() : $formName;
822 3
        if ($scope === '' && !empty($data)) {
823 2
            $this->setAttributes($data);
824
825 2
            return true;
826 2
        } elseif (isset($data[$scope])) {
827 2
            $this->setAttributes($data[$scope]);
828
829 2
            return true;
830
        }
831 2
        return false;
832
    }
833
834
    /**
835
     * Populates a set of models with the data from end user.
836
     * This method is mainly used to collect tabular data input.
837
     * The data to be loaded for each model is `$data[formName][index]`, where `formName`
838
     * refers to the value of [[formName()]], and `index` the index of the model in the `$models` array.
839
     * If [[formName()]] is empty, `$data[index]` will be used to populate each model.
840
     * The data being populated to each model is subject to the safety check by [[setAttributes()]].
841
     * @param array $models the models to be populated. Note that all models should have the same class.
842
     * @param array $data the data array. This is usually `$_POST` or `$_GET`, but can also be any valid array
843
     * supplied by end user.
844
     * @param string $formName the form name to be used for loading the data into the models.
845
     * If not set, it will use the [[formName()]] value of the first model in `$models`.
846
     * This parameter is available since version 2.0.1.
847
     * @return bool whether at least one of the models is successfully populated.
848
     */
849 1
    public static function loadMultiple($models, $data, $formName = null)
850
    {
851 1
        if ($formName === null) {
852
            /* @var $first Model|false */
853 1
            $first = reset($models);
854 1
            if ($first === false) {
855
                return false;
856
            }
857 1
            $formName = $first->formName();
858
        }
859
860 1
        $success = false;
861 1
        foreach ($models as $i => $model) {
862
            /* @var $model Model */
863 1
            if ($formName == '') {
864 1
                if (!empty($data[$i]) && $model->load($data[$i], '')) {
865 1
                    $success = true;
866
                }
867 1
            } elseif (!empty($data[$formName][$i]) && $model->load($data[$formName][$i], '')) {
868 1
                $success = true;
869
            }
870
        }
871
872 1
        return $success;
873
    }
874
875
    /**
876
     * Validates multiple models.
877
     * This method will validate every model. The models being validated may
878
     * be of the same or different types.
879
     * @param array $models the models to be validated
880
     * @param array $attributeNames list of attribute names that should be validated.
881
     * If this parameter is empty, it means any attribute listed in the applicable
882
     * validation rules should be validated.
883
     * @return bool whether all models are valid. False will be returned if one
884
     * or multiple models have validation error.
885
     */
886
    public static function validateMultiple($models, $attributeNames = null)
887
    {
888
        $valid = true;
889
        /* @var $model Model */
890
        foreach ($models as $model) {
891
            $valid = $model->validate($attributeNames) && $valid;
892
        }
893
894
        return $valid;
895
    }
896
897
    /**
898
     * Returns the list of fields that should be returned by default by [[toArray()]] when no specific fields are specified.
899
     *
900
     * A field is a named element in the returned array by [[toArray()]].
901
     *
902
     * This method should return an array of field names or field definitions.
903
     * If the former, the field name will be treated as an object property name whose value will be used
904
     * as the field value. If the latter, the array key should be the field name while the array value should be
905
     * the corresponding field definition which can be either an object property name or a PHP callable
906
     * returning the corresponding field value. The signature of the callable should be:
907
     *
908
     * ```php
909
     * function ($model, $field) {
910
     *     // return field value
911
     * }
912
     * ```
913
     *
914
     * For example, the following code declares four fields:
915
     *
916
     * - `email`: the field name is the same as the property name `email`;
917
     * - `firstName` and `lastName`: the field names are `firstName` and `lastName`, and their
918
     *   values are obtained from the `first_name` and `last_name` properties;
919
     * - `fullName`: the field name is `fullName`. Its value is obtained by concatenating `first_name`
920
     *   and `last_name`.
921
     *
922
     * ```php
923
     * return [
924
     *     'email',
925
     *     'firstName' => 'first_name',
926
     *     'lastName' => 'last_name',
927
     *     'fullName' => function ($model) {
928
     *         return $model->first_name . ' ' . $model->last_name;
929
     *     },
930
     * ];
931
     * ```
932
     *
933
     * In this method, you may also want to return different lists of fields based on some context
934
     * information. For example, depending on [[scenario]] or the privilege of the current application user,
935
     * you may return different sets of visible fields or filter out some fields.
936
     *
937
     * The default implementation of this method returns [[attributes()]] indexed by the same attribute names.
938
     *
939
     * @return array the list of field names or field definitions.
940
     * @see toArray()
941
     */
942
    public function fields()
943
    {
944
        $fields = $this->attributes();
945
946
        return array_combine($fields, $fields);
947
    }
948
949
    /**
950
     * Returns an iterator for traversing the attributes in the model.
951
     * This method is required by the interface [[\IteratorAggregate]].
952
     * @return ArrayIterator an iterator for traversing the items in the list.
953
     */
954 4
    public function getIterator()
955
    {
956 4
        $attributes = $this->getAttributes();
957 4
        return new ArrayIterator($attributes);
958
    }
959
960
    /**
961
     * Returns whether there is an element at the specified offset.
962
     * This method is required by the SPL interface [[\ArrayAccess]].
963
     * It is implicitly called when you use something like `isset($model[$offset])`.
964
     * @param mixed $offset the offset to check on.
965
     * @return bool whether or not an offset exists.
966
     */
967 1
    public function offsetExists($offset)
968
    {
969 1
        return isset($this->$offset);
970
    }
971
972
    /**
973
     * Returns the element at the specified offset.
974
     * This method is required by the SPL interface [[\ArrayAccess]].
975
     * It is implicitly called when you use something like `$value = $model[$offset];`.
976
     * @param mixed $offset the offset to retrieve element.
977
     * @return mixed the element at the offset, null if no element is found at the offset
978
     */
979 139
    public function offsetGet($offset)
980
    {
981 139
        return $this->$offset;
982
    }
983
984
    /**
985
     * Sets the element at the specified offset.
986
     * This method is required by the SPL interface [[\ArrayAccess]].
987
     * It is implicitly called when you use something like `$model[$offset] = $item;`.
988
     * @param int $offset the offset to set element
989
     * @param mixed $item the element value
990
     */
991 4
    public function offsetSet($offset, $item)
992
    {
993 4
        $this->$offset = $item;
994 4
    }
995
996
    /**
997
     * Sets the element value at the specified offset to null.
998
     * This method is required by the SPL interface [[\ArrayAccess]].
999
     * It is implicitly called when you use something like `unset($model[$offset])`.
1000
     * @param mixed $offset the offset to unset element
1001
     */
1002 1
    public function offsetUnset($offset)
1003
    {
1004 1
        $this->$offset = null;
1005 1
    }
1006
}
1007