Completed
Push — master ( f1a1d9...18cd95 )
by Paweł
30s queued 17s
created

framework/base/Model.php (2 issues)

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

758
    public function onUnsafeAttribute($name, /** @scrutinizer ignore-unused */ $value)

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

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