Passed
Pull Request — master (#19918)
by
unknown
09:42 queued 45s
created

BaseActiveRecord::afterSave()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\InvalidArgumentException;
12
use yii\base\InvalidCallException;
13
use yii\base\InvalidConfigException;
14
use yii\base\InvalidParamException;
15
use yii\base\Model;
16
use yii\base\ModelEvent;
17
use yii\base\NotSupportedException;
18
use yii\base\UnknownMethodException;
19
use yii\helpers\ArrayHelper;
20
21
/**
22
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
23
 *
24
 * See [[\yii\db\ActiveRecord]] for a concrete implementation.
25
 *
26
 * @property-read array $dirtyAttributes The changed attribute values (name-value pairs).
27
 * @property bool $isNewRecord Whether the record is new and should be inserted when calling [[save()]].
28
 * @property array $oldAttributes The old attribute values (name-value pairs). Note that the type of this
29
 * property differs in getter and setter. See [[getOldAttributes()]] and [[setOldAttributes()]] for details.
30
 * @property-read mixed $oldPrimaryKey The old primary key value. An array (column name => column value) is
31
 * returned if the primary key is composite or `$asArray` is `true`. A string is returned otherwise (null will be
32
 * returned if the key value is null).
33
 * @property-read mixed $primaryKey The primary key value. An array (column name => column value) is returned
34
 * if the primary key is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned
35
 * if the key value is null).
36
 * @property-read array $relatedRecords An array of related records indexed by relation names.
37
 *
38
 * @author Qiang Xue <[email protected]>
39
 * @author Carsten Brandt <[email protected]>
40
 * @since 2.0
41
 */
42
abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
43
{
44
    /**
45
     * @event Event an event that is triggered when the record is initialized via [[init()]].
46
     */
47
    const EVENT_INIT = 'init';
48
    /**
49
     * @event Event an event that is triggered after the record is created and populated with query result.
50
     */
51
    const EVENT_AFTER_FIND = 'afterFind';
52
    /**
53
     * @event ModelEvent an event that is triggered before inserting a record.
54
     * You may set [[ModelEvent::isValid]] to be `false` to stop the insertion.
55
     */
56
    const EVENT_BEFORE_INSERT = 'beforeInsert';
57
    /**
58
     * @event AfterSaveEvent an event that is triggered after a record is inserted.
59
     */
60
    const EVENT_AFTER_INSERT = 'afterInsert';
61
    /**
62
     * @event ModelEvent an event that is triggered before updating a record.
63
     * You may set [[ModelEvent::isValid]] to be `false` to stop the update.
64
     */
65
    const EVENT_BEFORE_UPDATE = 'beforeUpdate';
66
    /**
67
     * @event AfterSaveEvent an event that is triggered after a record is updated.
68
     */
69
    const EVENT_AFTER_UPDATE = 'afterUpdate';
70
    /**
71
     * @event ModelEvent an event that is triggered before deleting a record.
72
     * You may set [[ModelEvent::isValid]] to be `false` to stop the deletion.
73
     */
74
    const EVENT_BEFORE_DELETE = 'beforeDelete';
75
    /**
76
     * @event Event an event that is triggered after a record is deleted.
77
     */
78
    const EVENT_AFTER_DELETE = 'afterDelete';
79
    /**
80
     * @event Event an event that is triggered after a record is refreshed.
81
     * @since 2.0.8
82
     */
83
    const EVENT_AFTER_REFRESH = 'afterRefresh';
84
85
    /**
86
     * @var array attribute values indexed by attribute names
87
     */
88
    private $_attributes = [];
89
    /**
90
     * @var array|null old attribute values indexed by attribute names.
91
     * This is `null` if the record [[isNewRecord|is new]].
92
     */
93
    private $_oldAttributes;
94
    /**
95
     * @var array related models indexed by the relation names
96
     */
97
    private $_related = [];
98
    /**
99
     * @var array relation names indexed by their link attributes
100
     */
101
    private $_relationsDependencies = [];
102
103
104
    /**
105
     * {@inheritdoc}
106
     * @return static|null ActiveRecord instance matching the condition, or `null` if nothing matches.
107
     */
108 202
    public static function findOne($condition)
109
    {
110 202
        return static::findByCondition($condition)->one();
0 ignored issues
show
Bug Best Practice introduced by
The expression return static::findByCondition($condition)->one() also could return the type array which is incompatible with the documented return type null|yii\db\BaseActiveRecord.
Loading history...
111
    }
112
113
    /**
114
     * {@inheritdoc}
115
     * @return static[] an array of ActiveRecord instances, or an empty array if nothing matches.
116
     */
117 6
    public static function findAll($condition)
118
    {
119 6
        return static::findByCondition($condition)->all();
120
    }
121
122
    /**
123
     * Finds ActiveRecord instance(s) by the given condition.
124
     * This method is internally called by [[findOne()]] and [[findAll()]].
125
     * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter
126
     * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance.
127
     * @throws InvalidConfigException if there is no primary key defined
128
     * @internal
129
     */
130
    protected static function findByCondition($condition)
131
    {
132
        $query = static::find();
133
134
        if (!ArrayHelper::isAssociative($condition) && !$condition instanceof ExpressionInterface) {
135
            // query by primary key
136
            $primaryKey = static::primaryKey();
137
            if (isset($primaryKey[0])) {
138
                // if condition is scalar, search for a single primary key, if it is array, search for multiple primary key values
139
                $condition = [$primaryKey[0] => is_array($condition) ? array_values($condition) : $condition];
140
            } else {
141
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
142
            }
143
        }
144
145
        return $query->andWhere($condition);
146
    }
147
148
    /**
149
     * Updates the whole table using the provided attribute values and conditions.
150
     *
151
     * For example, to change the status to be 1 for all customers whose status is 2:
152
     *
153
     * ```php
154
     * Customer::updateAll(['status' => 1], 'status = 2');
155
     * ```
156
     *
157
     * @param array $attributes attribute values (name-value pairs) to be saved into the table
158
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
159
     * Please refer to [[Query::where()]] on how to specify this parameter.
160
     * @return int the number of rows updated
161
     * @throws NotSupportedException if not overridden
162
     */
163
    public static function updateAll($attributes, $condition = '')
164
    {
165
        throw new NotSupportedException(__METHOD__ . ' is not supported.');
166
    }
167
168
    /**
169
     * Updates the whole table using the provided counter changes and conditions.
170
     *
171
     * For example, to increment all customers' age by 1,
172
     *
173
     * ```php
174
     * Customer::updateAllCounters(['age' => 1]);
175
     * ```
176
     *
177
     * @param array $counters the counters to be updated (attribute name => increment value).
178
     * Use negative values if you want to decrement the counters.
179
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
180
     * Please refer to [[Query::where()]] on how to specify this parameter.
181
     * @return int the number of rows updated
182
     * @throws NotSupportedException if not overrided
183
     */
184
    public static function updateAllCounters($counters, $condition = '')
185
    {
186
        throw new NotSupportedException(__METHOD__ . ' is not supported.');
187
    }
188
189
    /**
190
     * Deletes rows in the table using the provided conditions.
191
     * WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
192
     *
193
     * For example, to delete all customers whose status is 3:
194
     *
195
     * ```php
196
     * Customer::deleteAll('status = 3');
197
     * ```
198
     *
199
     * @param string|array|null $condition the conditions that will be put in the WHERE part of the DELETE SQL.
200
     * Please refer to [[Query::where()]] on how to specify this parameter.
201
     * @return int the number of rows deleted
202
     * @throws NotSupportedException if not overridden.
203
     */
204
    public static function deleteAll($condition = null)
205
    {
206
        throw new NotSupportedException(__METHOD__ . ' is not supported.');
207
    }
208
209
    /**
210
     * Returns the name of the column that stores the lock version for implementing optimistic locking.
211
     *
212
     * Optimistic locking allows multiple users to access the same record for edits and avoids
213
     * potential conflicts. In case when a user attempts to save the record upon some staled data
214
     * (because another user has modified the data), a [[StaleObjectException]] exception will be thrown,
215
     * and the update or deletion is skipped.
216
     *
217
     * Optimistic locking is only supported by [[update()]] and [[delete()]].
218
     *
219
     * To use Optimistic locking:
220
     *
221
     * 1. Create a column to store the version number of each row. The column type should be `BIGINT DEFAULT 0`.
222
     *    Override this method to return the name of this column.
223
     * 2. Ensure the version value is submitted and loaded to your model before any update or delete.
224
     *    Or add [[\yii\behaviors\OptimisticLockBehavior|OptimisticLockBehavior]] to your model
225
     *    class in order to automate the process.
226
     * 3. In the Web form that collects the user input, add a hidden field that stores
227
     *    the lock version of the record being updated.
228
     * 4. In the controller action that does the data updating, try to catch the [[StaleObjectException]]
229
     *    and implement necessary business logic (e.g. merging the changes, prompting stated data)
230
     *    to resolve the conflict.
231
     *
232
     * @return string|null the column name that stores the lock version of a table row.
233
     * If `null` is returned (default implemented), optimistic locking will not be supported.
234
     */
235 37
    public function optimisticLock()
236
    {
237 37
        return null;
238
    }
239
240
    /**
241
     * {@inheritdoc}
242
     */
243 3
    public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
244
    {
245 3
        if (parent::canGetProperty($name, $checkVars, $checkBehaviors)) {
246 3
            return true;
247
        }
248
249
        try {
250 3
            return $this->hasAttribute($name);
251
        } catch (\Exception $e) {
252
            // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used
253
            return false;
254
        }
255
    }
256
257
    /**
258
     * {@inheritdoc}
259
     */
260 9
    public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
261
    {
262 9
        if (parent::canSetProperty($name, $checkVars, $checkBehaviors)) {
263 6
            return true;
264
        }
265
266
        try {
267 3
            return $this->hasAttribute($name);
268
        } catch (\Exception $e) {
269
            // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used
270
            return false;
271
        }
272
    }
273
274
    /**
275
     * PHP getter magic method.
276
     * This method is overridden so that attributes and related objects can be accessed like properties.
277
     *
278
     * @param string $name property name
279
     * @throws InvalidArgumentException if relation name is wrong
280
     * @return mixed property value
281
     * @see getAttribute()
282
     */
283 459
    public function __get($name)
284
    {
285 459
        if (isset($this->_attributes[$name]) || array_key_exists($name, $this->_attributes)) {
286 438
            return $this->_attributes[$name];
287
        }
288
289 231
        if ($this->hasAttribute($name)) {
290 44
            return null;
291
        }
292
293 208
        if (isset($this->_related[$name]) || array_key_exists($name, $this->_related)) {
294 130
            return $this->_related[$name];
295
        }
296 142
        $value = parent::__get($name);
297 133
        if ($value instanceof ActiveQueryInterface) {
298 88
            return $this->_related[$name] = $value->findFor($name, $this);
299
        }
300
301 54
        return $value;
302
    }
303
304
    /**
305
     * PHP setter magic method.
306
     * This method is overridden so that AR attributes can be accessed like properties.
307
     * @param string $name property name
308
     * @param mixed $value property value
309
     */
310 294
    public function __set($name, $value)
311
    {
312 294
        if ($this->hasAttribute($name)) {
313 294
            $this->_attributes[$name] = $value;
314
        } else {
315 6
            parent::__set($name, $value);
316
        }
317 294
    }
318
319
    /**
320
     * Checks if a property value is null.
321
     * This method overrides the parent implementation by checking if the named attribute is `null` or not.
322
     * @param string $name the property name or the event name
323
     * @return bool whether the property value is null
324
     */
325 251
    public function __isset($name)
326
    {
327
        try {
328 251
            return $this->__get($name) !== null;
329 13
        } catch (\Exception $t) {
330 13
            return false;
331
        } catch (\Throwable $e) {
332
            return false;
333
        }
334
    }
335
336
    /**
337
     * Sets a component property to be null.
338
     * This method overrides the parent implementation by clearing
339
     * the specified attribute value.
340
     * @param string $name the property name or the event name
341
     */
342 15
    public function __unset($name)
343
    {
344 15
        if ($this->hasAttribute($name)) {
345 9
            unset($this->_attributes[$name]);
346 6
        } elseif (array_key_exists($name, $this->_related)) {
347 6
            unset($this->_related[$name]);
348
        } elseif ($this->getRelation($name, false) === null) {
349
            parent::__unset($name);
350
        }
351 15
    }
352
353
    /**
354
     * Declares a `has-one` relation.
355
     * The declaration is returned in terms of a relational [[ActiveQuery]] instance
356
     * through which the related record can be queried and retrieved back.
357
     *
358
     * A `has-one` relation means that there is at most one related record matching
359
     * the criteria set by this relation, e.g., a customer has one country.
360
     *
361
     * For example, to declare the `country` relation for `Customer` class, we can write
362
     * the following code in the `Customer` class:
363
     *
364
     * ```php
365
     * public function getCountry()
366
     * {
367
     *     return $this->hasOne(Country::class, ['id' => 'country_id']);
368
     * }
369
     * ```
370
     *
371
     * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name
372
     * in the related class `Country`, while the 'country_id' value refers to an attribute name
373
     * in the current AR class.
374
     *
375
     * Call methods declared in [[ActiveQuery]] to further customize the relation.
376
     *
377
     * @param string $class the class name of the related record
378
     * @param array $link the primary-foreign key constraint. The keys of the array refer to
379
     * the attributes of the record associated with the `$class` model, while the values of the
380
     * array refer to the corresponding attributes in **this** AR class.
381
     * @return ActiveQueryInterface the relational query object.
382
     */
383 106
    public function hasOne($class, $link)
384
    {
385 106
        return $this->createRelationQuery($class, $link, false);
386
    }
387
388
    /**
389
     * Declares a `has-many` relation.
390
     * The declaration is returned in terms of a relational [[ActiveQuery]] instance
391
     * through which the related record can be queried and retrieved back.
392
     *
393
     * A `has-many` relation means that there are multiple related records matching
394
     * the criteria set by this relation, e.g., a customer has many orders.
395
     *
396
     * For example, to declare the `orders` relation for `Customer` class, we can write
397
     * the following code in the `Customer` class:
398
     *
399
     * ```php
400
     * public function getOrders()
401
     * {
402
     *     return $this->hasMany(Order::class, ['customer_id' => 'id']);
403
     * }
404
     * ```
405
     *
406
     * Note that in the above, the 'customer_id' key in the `$link` parameter refers to
407
     * an attribute name in the related class `Order`, while the 'id' value refers to
408
     * an attribute name in the current AR class.
409
     *
410
     * Call methods declared in [[ActiveQuery]] to further customize the relation.
411
     *
412
     * @param string $class the class name of the related record
413
     * @param array $link the primary-foreign key constraint. The keys of the array refer to
414
     * the attributes of the record associated with the `$class` model, while the values of the
415
     * array refer to the corresponding attributes in **this** AR class.
416
     * @return ActiveQueryInterface the relational query object.
417
     */
418 180
    public function hasMany($class, $link)
419
    {
420 180
        return $this->createRelationQuery($class, $link, true);
421
    }
422
423
    /**
424
     * Creates a query instance for `has-one` or `has-many` relation.
425
     * @param string $class the class name of the related record.
426
     * @param array $link the primary-foreign key constraint.
427
     * @param bool $multiple whether this query represents a relation to more than one record.
428
     * @return ActiveQueryInterface the relational query object.
429
     * @since 2.0.12
430
     * @see hasOne()
431
     * @see hasMany()
432
     */
433 235
    protected function createRelationQuery($class, $link, $multiple)
434
    {
435
        /* @var $class ActiveRecordInterface */
436
        /* @var $query ActiveQuery */
437 235
        $query = $class::find();
438 235
        $query->primaryModel = $this;
0 ignored issues
show
Documentation Bug introduced by
$this is of type yii\db\BaseActiveRecord, but the property $primaryModel was declared to be of type yii\db\ActiveRecord. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
439 235
        $query->link = $link;
440 235
        $query->multiple = $multiple;
441 235
        return $query;
442
    }
443
444
    /**
445
     * Populates the named relation with the related records.
446
     * Note that this method does not check if the relation exists or not.
447
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
448
     * @param ActiveRecordInterface|array|null $records the related records to be populated into the relation.
449
     * @see getRelation()
450
     */
451 150
    public function populateRelation($name, $records)
452
    {
453 150
        $this->_related[$name] = $records;
454 150
    }
455
456
    /**
457
     * Check whether the named relation has been populated with records.
458
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
459
     * @return bool whether relation has been populated with records.
460
     * @see getRelation()
461
     */
462 93
    public function isRelationPopulated($name)
463
    {
464 93
        return array_key_exists($name, $this->_related);
465
    }
466
467
    /**
468
     * Returns all populated related records.
469
     * @return array an array of related records indexed by relation names.
470
     * @see getRelation()
471
     */
472 6
    public function getRelatedRecords()
473
    {
474 6
        return $this->_related;
475
    }
476
477
    /**
478
     * Returns a value indicating whether the model has an attribute with the specified name.
479
     * @param string $name the name of the attribute
480
     * @return bool whether the model has an attribute with the specified name.
481
     */
482 359
    public function hasAttribute($name)
483
    {
484 359
        return isset($this->_attributes[$name]) || in_array($name, $this->attributes(), true);
485
    }
486
487
    /**
488
     * Returns the named attribute value.
489
     * If this record is the result of a query and the attribute is not loaded,
490
     * `null` will be returned.
491
     * @param string $name the attribute name
492
     * @return mixed the attribute value. `null` if the attribute is not set or does not exist.
493
     * @see hasAttribute()
494
     */
495 4
    public function getAttribute($name)
496
    {
497 4
        return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
498
    }
499
500
    /**
501
     * Sets the named attribute value.
502
     * @param string $name the attribute name
503
     * @param mixed $value the attribute value.
504
     * @throws InvalidArgumentException if the named attribute does not exist.
505
     * @see hasAttribute()
506
     */
507 97
    public function setAttribute($name, $value)
508
    {
509 97
        if ($this->hasAttribute($name)) {
510 97
            $this->_attributes[$name] = $value;
511
        } else {
512
            throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
513
        }
514 97
    }
515
516
    /**
517
     * Returns the old attribute values.
518
     * @return array the old attribute values (name-value pairs)
519
     */
520
    public function getOldAttributes()
521
    {
522
        return $this->_oldAttributes === null ? [] : $this->_oldAttributes;
523
    }
524
525
    /**
526
     * Sets the old attribute values.
527
     * All existing old attribute values will be discarded.
528
     * @param array|null $values old attribute values to be set.
529
     * If set to `null` this record is considered to be [[isNewRecord|new]].
530
     */
531 105
    public function setOldAttributes($values)
532
    {
533 105
        $this->_oldAttributes = $values;
534 105
    }
535
536
    /**
537
     * Returns the old value of the named attribute.
538
     * If this record is the result of a query and the attribute is not loaded,
539
     * `null` will be returned.
540
     * @param string $name the attribute name
541
     * @return mixed the old attribute value. `null` if the attribute is not loaded before
542
     * or does not exist.
543
     * @see hasAttribute()
544
     */
545
    public function getOldAttribute($name)
546
    {
547
        return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
548
    }
549
550
    /**
551
     * Sets the old value of the named attribute.
552
     * @param string $name the attribute name
553
     * @param mixed $value the old attribute value.
554
     * @throws InvalidArgumentException if the named attribute does not exist.
555
     * @see hasAttribute()
556
     */
557 120
    public function setOldAttribute($name, $value)
558
    {
559 120
        if ($this->canSetOldAttribute($name)) {
560 120
            $this->_oldAttributes[$name] = $value;
561
        } else {
562
            throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
563
        }
564 120
    }
565
566
    /**
567
     * Returns if the old named attribute can be set.
568
     * @param string $name the attribute name
569
     * @return bool whether the old attribute can be set
570
     * @see setOldAttribute()
571
     */
572 120
    public function canSetOldAttribute($name)
573
    {
574 120
        return (isset($this->_oldAttributes[$name]) || $this->hasAttribute($name));
575
    }
576
577
    /**
578
     * Marks an attribute dirty.
579
     * This method may be called to force updating a record when calling [[update()]],
580
     * even if there is no change being made to the record.
581
     * @param string $name the attribute name
582
     */
583 7
    public function markAttributeDirty($name)
584
    {
585 7
        unset($this->_oldAttributes[$name]);
586 7
    }
587
588
    /**
589
     * Returns a value indicating whether the named attribute has been changed.
590
     * @param string $name the name of the attribute.
591
     * @param bool $identical whether the comparison of new and old value is made for
592
     * identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison.
593
     * This parameter is available since version 2.0.4.
594
     * @return bool whether the attribute has been changed
595
     */
596 2
    public function isAttributeChanged($name, $identical = true)
597
    {
598 2
        if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) {
599 1
            if ($identical) {
600 1
                return $this->_attributes[$name] !== $this->_oldAttributes[$name];
601
            }
602
603
            return $this->_attributes[$name] != $this->_oldAttributes[$name];
604
        }
605
606 1
        return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]);
607
    }
608
609
    /**
610
     * Returns the attribute values that have been modified since they are loaded or saved most recently.
611
     *
612
     * The comparison of new and old values is made for identical values using `===`.
613
     *
614
     * @param string[]|null $names the names of the attributes whose values may be returned if they are
615
     * changed recently. If null, [[attributes()]] will be used.
616
     * @return array the changed attribute values (name-value pairs)
617
     */
618 116
    public function getDirtyAttributes($names = null)
619
    {
620 116
        if ($names === null) {
621 113
            $names = $this->attributes();
622
        }
623 116
        $names = array_flip($names);
624 116
        $attributes = [];
625 116
        if ($this->_oldAttributes === null) {
626 102
            foreach ($this->_attributes as $name => $value) {
627 98
                if (isset($names[$name])) {
628 98
                    $attributes[$name] = $value;
629
                }
630
            }
631
        } else {
632 47
            foreach ($this->_attributes as $name => $value) {
633 47
                if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $this->isValueDifferent($value, $this->_oldAttributes[$name]))) {
634 43
                    $attributes[$name] = $value;
635
                }
636
            }
637
        }
638
639 116
        return $attributes;
640
    }
641
642
    /**
643
     * Saves the current record.
644
     *
645
     * This method will call [[insert()]] when [[isNewRecord]] is `true`, or [[update()]]
646
     * when [[isNewRecord]] is `false`.
647
     *
648
     * For example, to save a customer record:
649
     *
650
     * ```php
651
     * $customer = new Customer; // or $customer = Customer::findOne($id);
652
     * $customer->name = $name;
653
     * $customer->email = $email;
654
     * $customer->save();
655
     * ```
656
     *
657
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
658
     * before saving the record. Defaults to `true`. If the validation fails, the record
659
     * will not be saved to the database and this method will return `false`.
660
     * @param array|null $attributeNames list of attribute names that need to be saved. Defaults to null,
661
     * meaning all attributes that are loaded from DB will be saved.
662
     * @return bool whether the saving succeeded (i.e. no validation errors occurred).
663
     */
664 110
    public function save($runValidation = true, $attributeNames = null)
665
    {
666 110
        if ($this->getIsNewRecord()) {
667 96
            return $this->insert($runValidation, $attributeNames);
668
        }
669
670 31
        return $this->update($runValidation, $attributeNames) !== false;
671
    }
672
673
    /**
674
     * Saves the changes to this active record into the associated database table.
675
     *
676
     * This method performs the following steps in order:
677
     *
678
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
679
     *    returns `false`, the rest of the steps will be skipped;
680
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
681
     *    failed, the rest of the steps will be skipped;
682
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
683
     *    the rest of the steps will be skipped;
684
     * 4. save the record into database. If this fails, it will skip the rest of the steps;
685
     * 5. call [[afterSave()]];
686
     *
687
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
688
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
689
     * will be raised by the corresponding methods.
690
     *
691
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
692
     *
693
     * For example, to update a customer record:
694
     *
695
     * ```php
696
     * $customer = Customer::findOne($id);
697
     * $customer->name = $name;
698
     * $customer->email = $email;
699
     * $customer->update();
700
     * ```
701
     *
702
     * Note that it is possible the update does not affect any row in the table.
703
     * In this case, this method will return 0. For this reason, you should use the following
704
     * code to check if update() is successful or not:
705
     *
706
     * ```php
707
     * if ($customer->update() !== false) {
708
     *     // update successful
709
     * } else {
710
     *     // update failed
711
     * }
712
     * ```
713
     *
714
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
715
     * before saving the record. Defaults to `true`. If the validation fails, the record
716
     * will not be saved to the database and this method will return `false`.
717
     * @param array|null $attributeNames list of attribute names that need to be saved. Defaults to null,
718
     * meaning all attributes that are loaded from DB will be saved.
719
     * @return int|false the number of rows affected, or `false` if validation fails
720
     * or [[beforeSave()]] stops the updating process.
721
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
722
     * being updated is outdated.
723
     * @throws Exception in case update failed.
724
     */
725
    public function update($runValidation = true, $attributeNames = null)
726
    {
727
        if ($runValidation && !$this->validate($attributeNames)) {
728
            return false;
729
        }
730
731
        return $this->updateInternal($attributeNames);
732
    }
733
734
    /**
735
     * Updates the specified attributes.
736
     *
737
     * This method is a shortcut to [[update()]] when data validation is not needed
738
     * and only a small set attributes need to be updated.
739
     *
740
     * You may specify the attributes to be updated as name list or name-value pairs.
741
     * If the latter, the corresponding attribute values will be modified accordingly.
742
     * The method will then save the specified attributes into database.
743
     *
744
     * Note that this method will **not** perform data validation and will **not** trigger events.
745
     *
746
     * @param array $attributes the attributes (names or name-value pairs) to be updated
747
     * @return int the number of rows affected.
748
     */
749 7
    public function updateAttributes($attributes)
750
    {
751 7
        $attrs = [];
752 7
        foreach ($attributes as $name => $value) {
753 7
            if (is_int($name)) {
754
                $attrs[] = $value;
755
            } else {
756 7
                $this->$name = $value;
757 7
                $attrs[] = $name;
758
            }
759
        }
760
761 7
        $values = $this->getDirtyAttributes($attrs);
762 7
        if (empty($values) || $this->getIsNewRecord()) {
763 4
            return 0;
764
        }
765
766 6
        $rows = static::updateAll($values, $this->getOldPrimaryKey(true));
767
768 6
        foreach ($values as $name => $value) {
769 6
            $this->_oldAttributes[$name] = $this->_attributes[$name];
770
        }
771
772 6
        return $rows;
773
    }
774
775
    /**
776
     * @see update()
777
     * @param array|null $attributes attributes to update
778
     * @return int|false the number of rows affected, or false if [[beforeSave()]] stops the updating process.
779
     * @throws StaleObjectException
780
     */
781 41
    protected function updateInternal($attributes = null)
782
    {
783 41
        if (!$this->beforeSave(false)) {
784
            return false;
785
        }
786 41
        $values = $this->getDirtyAttributes($attributes);
787 41
        if (empty($values)) {
788 3
            $this->afterSave(false, $values);
789 3
            return 0;
790
        }
791 39
        $condition = $this->getOldPrimaryKey(true);
792 39
        $lock = $this->optimisticLock();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $lock is correct as $this->optimisticLock() targeting yii\db\BaseActiveRecord::optimisticLock() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
793 39
        if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
794 5
            $values[$lock] = $this->$lock + 1;
795 5
            $condition[$lock] = $this->$lock;
796
        }
797
        // We do not check the return value of updateAll() because it's possible
798
        // that the UPDATE statement doesn't change anything and thus returns 0.
799 39
        $rows = static::updateAll($values, $condition);
800
801 39
        if ($lock !== null && !$rows) {
802 4
            throw new StaleObjectException('The object being updated is outdated.');
803
        }
804
805 39
        if (isset($values[$lock])) {
806 5
            $this->$lock = $values[$lock];
807
        }
808
809 39
        $changedAttributes = [];
810 39
        foreach ($values as $name => $value) {
811 39
            $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
812 39
            $this->_oldAttributes[$name] = $value;
813
        }
814 39
        $this->afterSave(false, $changedAttributes);
815
816 39
        return $rows;
817
    }
818
819
    /**
820
     * Updates one or several counter columns for the current AR object.
821
     * Note that this method differs from [[updateAllCounters()]] in that it only
822
     * saves counters for the current AR object.
823
     *
824
     * An example usage is as follows:
825
     *
826
     * ```php
827
     * $post = Post::findOne($id);
828
     * $post->updateCounters(['view_count' => 1]);
829
     * ```
830
     *
831
     * @param array $counters the counters to be updated (attribute name => increment value)
832
     * Use negative values if you want to decrement the counters.
833
     * @return bool whether the saving is successful
834
     * @see updateAllCounters()
835
     */
836 6
    public function updateCounters($counters)
837
    {
838 6
        if (static::updateAllCounters($counters, $this->getOldPrimaryKey(true)) > 0) {
839 6
            foreach ($counters as $name => $value) {
840 6
                if (!isset($this->_attributes[$name])) {
841 3
                    $this->_attributes[$name] = $value;
842
                } else {
843 3
                    $this->_attributes[$name] += $value;
844
                }
845 6
                $this->_oldAttributes[$name] = $this->_attributes[$name];
846
            }
847
848 6
            return true;
849
        }
850
851
        return false;
852
    }
853
854
    /**
855
     * Deletes the table row corresponding to this active record.
856
     *
857
     * This method performs the following steps in order:
858
     *
859
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
860
     *    rest of the steps;
861
     * 2. delete the record from the database;
862
     * 3. call [[afterDelete()]].
863
     *
864
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
865
     * will be raised by the corresponding methods.
866
     *
867
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
868
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
869
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
870
     * being deleted is outdated.
871
     * @throws Exception in case delete failed.
872
     */
873
    public function delete()
874
    {
875
        $result = false;
876
        if ($this->beforeDelete()) {
877
            // we do not check the return value of deleteAll() because it's possible
878
            // the record is already deleted in the database and thus the method will return 0
879
            $condition = $this->getOldPrimaryKey(true);
880
            $lock = $this->optimisticLock();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $lock is correct as $this->optimisticLock() targeting yii\db\BaseActiveRecord::optimisticLock() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
881
            if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
882
                $condition[$lock] = $this->$lock;
883
            }
884
            $result = static::deleteAll($condition);
885
            if ($lock !== null && !$result) {
886
                throw new StaleObjectException('The object being deleted is outdated.');
887
            }
888
            $this->_oldAttributes = null;
889
            $this->afterDelete();
890
        }
891
892
        return $result;
893
    }
894
895
    /**
896
     * Returns a value indicating whether the current record is new.
897
     * @return bool whether the record is new and should be inserted when calling [[save()]].
898
     */
899 159
    public function getIsNewRecord()
900
    {
901 159
        return $this->_oldAttributes === null;
902
    }
903
904
    /**
905
     * Sets the value indicating whether the record is new.
906
     * @param bool $value whether the record is new and should be inserted when calling [[save()]].
907
     * @see getIsNewRecord()
908
     */
909
    public function setIsNewRecord($value)
910
    {
911
        $this->_oldAttributes = $value ? null : $this->_attributes;
912
    }
913
914
    /**
915
     * Initializes the object.
916
     * This method is called at the end of the constructor.
917
     * The default implementation will trigger an [[EVENT_INIT]] event.
918
     */
919 572
    public function init()
920
    {
921 572
        parent::init();
922 572
        $this->trigger(self::EVENT_INIT);
923 572
    }
924
925
    /**
926
     * This method is called when the AR object is created and populated with the query result.
927
     * The default implementation will trigger an [[EVENT_AFTER_FIND]] event.
928
     * When overriding this method, make sure you call the parent implementation to ensure the
929
     * event is triggered.
930
     */
931 381
    public function afterFind()
932
    {
933 381
        $this->trigger(self::EVENT_AFTER_FIND);
934 381
    }
935
936
    /**
937
     * This method is called at the beginning of inserting or updating a record.
938
     *
939
     * The default implementation will trigger an [[EVENT_BEFORE_INSERT]] event when `$insert` is `true`,
940
     * or an [[EVENT_BEFORE_UPDATE]] event if `$insert` is `false`.
941
     * When overriding this method, make sure you call the parent implementation like the following:
942
     *
943
     * ```php
944
     * public function beforeSave($insert)
945
     * {
946
     *     if (!parent::beforeSave($insert)) {
947
     *         return false;
948
     *     }
949
     *
950
     *     // ...custom code here...
951
     *     return true;
952
     * }
953
     * ```
954
     *
955
     * @param bool $insert whether this method called while inserting a record.
956
     * If `false`, it means the method is called while updating a record.
957
     * @return bool whether the insertion or updating should continue.
958
     * If `false`, the insertion or updating will be cancelled.
959
     */
960 122
    public function beforeSave($insert)
961
    {
962 122
        $event = new ModelEvent();
963 122
        $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
964
965 122
        return $event->isValid;
966
    }
967
968
    /**
969
     * This method is called at the end of inserting or updating a record.
970
     * The default implementation will trigger an [[EVENT_AFTER_INSERT]] event when `$insert` is `true`,
971
     * or an [[EVENT_AFTER_UPDATE]] event if `$insert` is `false`. The event class used is [[AfterSaveEvent]].
972
     * When overriding this method, make sure you call the parent implementation so that
973
     * the event is triggered.
974
     * @param bool $insert whether this method called while inserting a record.
975
     * If `false`, it means the method is called while updating a record.
976
     * @param array $changedAttributes The old values of attributes that had changed and were saved.
977
     * You can use this parameter to take action based on the changes made for example send an email
978
     * when the password had changed or implement audit trail that tracks all the changes.
979
     * `$changedAttributes` gives you the old attribute values while the active record (`$this`) has
980
     * already the new, updated values.
981
     *
982
     * Note that no automatic type conversion performed by default. You may use
983
     * [[\yii\behaviors\AttributeTypecastBehavior]] to facilitate attribute typecasting.
984
     * See https://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting.
985
     */
986 113
    public function afterSave($insert, $changedAttributes)
987
    {
988 113
        $this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE, new AfterSaveEvent([
989 113
            'changedAttributes' => $changedAttributes,
990
        ]));
991 113
    }
992
993
    /**
994
     * This method is invoked before deleting a record.
995
     *
996
     * The default implementation raises the [[EVENT_BEFORE_DELETE]] event.
997
     * When overriding this method, make sure you call the parent implementation like the following:
998
     *
999
     * ```php
1000
     * public function beforeDelete()
1001
     * {
1002
     *     if (!parent::beforeDelete()) {
1003
     *         return false;
1004
     *     }
1005
     *
1006
     *     // ...custom code here...
1007
     *     return true;
1008
     * }
1009
     * ```
1010
     *
1011
     * @return bool whether the record should be deleted. Defaults to `true`.
1012
     */
1013 7
    public function beforeDelete()
1014
    {
1015 7
        $event = new ModelEvent();
1016 7
        $this->trigger(self::EVENT_BEFORE_DELETE, $event);
1017
1018 7
        return $event->isValid;
1019
    }
1020
1021
    /**
1022
     * This method is invoked after deleting a record.
1023
     * The default implementation raises the [[EVENT_AFTER_DELETE]] event.
1024
     * You may override this method to do postprocessing after the record is deleted.
1025
     * Make sure you call the parent implementation so that the event is raised properly.
1026
     */
1027 7
    public function afterDelete()
1028
    {
1029 7
        $this->trigger(self::EVENT_AFTER_DELETE);
1030 7
    }
1031
1032
    /**
1033
     * Repopulates this active record with the latest data.
1034
     *
1035
     * If the refresh is successful, an [[EVENT_AFTER_REFRESH]] event will be triggered.
1036
     * This event is available since version 2.0.8.
1037
     *
1038
     * @return bool whether the row still exists in the database. If `true`, the latest data
1039
     * will be populated to this active record. Otherwise, this record will remain unchanged.
1040
     */
1041
    public function refresh()
1042
    {
1043
        /* @var $record BaseActiveRecord */
1044
        $record = static::findOne($this->getPrimaryKey(true));
1045
        return $this->refreshInternal($record);
1046
    }
1047
1048
    /**
1049
     * Repopulates this active record with the latest data from a newly fetched instance.
1050
     * @param BaseActiveRecord $record the record to take attributes from.
1051
     * @return bool whether refresh was successful.
1052
     * @see refresh()
1053
     * @since 2.0.13
1054
     */
1055 29
    protected function refreshInternal($record)
1056
    {
1057 29
        if ($record === null) {
1058 3
            return false;
1059
        }
1060 29
        foreach ($this->attributes() as $name) {
1061 29
            $this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null;
1062
        }
1063 29
        $this->_oldAttributes = $record->_oldAttributes;
1064 29
        $this->afterRefresh();
1065
1066 29
        return true;
1067
    }
1068
1069
    /**
1070
     * This method is called when the AR object is refreshed.
1071
     * The default implementation will trigger an [[EVENT_AFTER_REFRESH]] event.
1072
     * When overriding this method, make sure you call the parent implementation to ensure the
1073
     * event is triggered.
1074
     * @since 2.0.8
1075
     */
1076 29
    public function afterRefresh()
1077
    {
1078 29
        $this->trigger(self::EVENT_AFTER_REFRESH);
1079 29
    }
1080
1081
    /**
1082
     * Returns a value indicating whether the given active record is the same as the current one.
1083
     * The comparison is made by comparing the table names and the primary key values of the two active records.
1084
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
1085
     * @param ActiveRecordInterface $record record to compare to
1086
     * @return bool whether the two active records refer to the same row in the same database table.
1087
     */
1088
    public function equals($record)
1089
    {
1090
        if ($this->getIsNewRecord() || $record->getIsNewRecord()) {
1091
            return false;
1092
        }
1093
1094
        return get_class($this) === get_class($record) && $this->getPrimaryKey() === $record->getPrimaryKey();
1095
    }
1096
1097
    /**
1098
     * Returns the primary key value(s).
1099
     * @param bool $asArray whether to return the primary key value as an array. If `true`,
1100
     * the return value will be an array with column names as keys and column values as values.
1101
     * Note that for composite primary keys, an array will always be returned regardless of this parameter value.
1102
     * @return mixed the primary key value. An array (column name => column value) is returned if the primary key
1103
     * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
1104
     * the key value is null).
1105
     */
1106 51
    public function getPrimaryKey($asArray = false)
1107
    {
1108 51
        $keys = static::primaryKey();
1109 51
        if (!$asArray && count($keys) === 1) {
1110 25
            return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null;
1111
        }
1112
1113 29
        $values = [];
1114 29
        foreach ($keys as $name) {
1115 29
            $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
1116
        }
1117
1118 29
        return $values;
1119
    }
1120
1121
    /**
1122
     * Returns the old primary key value(s).
1123
     * This refers to the primary key value that is populated into the record
1124
     * after executing a find method (e.g. find(), findOne()).
1125
     * The value remains unchanged even if the primary key attribute is manually assigned with a different value.
1126
     * @param bool $asArray whether to return the primary key value as an array. If `true`,
1127
     * the return value will be an array with column name as key and column value as value.
1128
     * If this is `false` (default), a scalar value will be returned for non-composite primary key.
1129
     * @return mixed the old primary key value. An array (column name => column value) is returned if the primary key
1130
     * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
1131
     * the key value is null).
1132
     * @throws Exception if the AR model does not have a primary key
1133
     */
1134 77
    public function getOldPrimaryKey($asArray = false)
1135
    {
1136 77
        $keys = static::primaryKey();
1137 77
        if (empty($keys)) {
1138
            throw new Exception(get_class($this) . ' does not have a primary key. You should either define a primary key for the corresponding table or override the primaryKey() method.');
1139
        }
1140 77
        if (!$asArray && count($keys) === 1) {
1141
            return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null;
1142
        }
1143
1144 77
        $values = [];
1145 77
        foreach ($keys as $name) {
1146 77
            $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
1147
        }
1148
1149 77
        return $values;
1150
    }
1151
1152
    /**
1153
     * Populates an active record object using a row of data from the database/storage.
1154
     *
1155
     * This is an internal method meant to be called to create active record objects after
1156
     * fetching data from the database. It is mainly used by [[ActiveQuery]] to populate
1157
     * the query results into active records.
1158
     *
1159
     * When calling this method manually you should call [[afterFind()]] on the created
1160
     * record to trigger the [[EVENT_AFTER_FIND|afterFind Event]].
1161
     *
1162
     * @param BaseActiveRecord $record the record to be populated. In most cases this will be an instance
1163
     * created by [[instantiate()]] beforehand.
1164
     * @param array $row attribute values (name => value)
1165
     */
1166 381
    public static function populateRecord($record, $row)
1167
    {
1168 381
        $columns = array_flip($record->attributes());
1169 381
        foreach ($row as $name => $value) {
1170 381
            if (isset($columns[$name])) {
1171 381
                $record->_attributes[$name] = $value;
1172 6
            } elseif ($record->canSetProperty($name)) {
1173 6
                $record->$name = $value;
1174
            }
1175
        }
1176 381
        $record->_oldAttributes = $record->_attributes;
1177 381
    }
1178
1179
    /**
1180
     * Creates an active record instance.
1181
     *
1182
     * This method is called together with [[populateRecord()]] by [[ActiveQuery]].
1183
     * It is not meant to be used for creating new records directly.
1184
     *
1185
     * You may override this method if the instance being created
1186
     * depends on the row data to be populated into the record.
1187
     * For example, by creating a record based on the value of a column,
1188
     * you may implement the so-called single-table inheritance mapping.
1189
     * @param array $row row data to be populated into the record.
1190
     * @return static the newly created active record
1191
     */
1192 375
    public static function instantiate($row)
1193
    {
1194 375
        return new static();
1195
    }
1196
1197
    /**
1198
     * Returns whether there is an element at the specified offset.
1199
     * This method is required by the interface [[\ArrayAccess]].
1200
     * @param mixed $offset the offset to check on
1201
     * @return bool whether there is an element at the specified offset.
1202
     */
1203
    #[\ReturnTypeWillChange]
1204 236
    public function offsetExists($offset)
1205
    {
1206 236
        return $this->__isset($offset);
1207
    }
1208
1209
    /**
1210
     * Returns the relation object with the specified name.
1211
     * A relation is defined by a getter method which returns an [[ActiveQueryInterface]] object.
1212
     * It can be declared in either the Active Record class itself or one of its behaviors.
1213
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
1214
     * @param bool $throwException whether to throw exception if the relation does not exist.
1215
     * @return ActiveQueryInterface|ActiveQuery|null the relational query object. If the relation does not exist
1216
     * and `$throwException` is `false`, `null` will be returned.
1217
     * @throws InvalidArgumentException if the named relation does not exist.
1218
     */
1219 201
    public function getRelation($name, $throwException = true)
1220
    {
1221 201
        $getter = 'get' . $name;
1222
        try {
1223
            // the relation could be defined in a behavior
1224 201
            $relation = $this->$getter();
1225
        } catch (UnknownMethodException $e) {
1226
            if ($throwException) {
1227
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e);
1228
            }
1229
1230
            return null;
1231
        }
1232 201
        if (!$relation instanceof ActiveQueryInterface) {
1233
            if ($throwException) {
1234
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".');
1235
            }
1236
1237
            return null;
1238
        }
1239
1240 201
        if (method_exists($this, $getter)) {
1241
            // relation name is case sensitive, trying to validate it when the relation is defined within this class
1242 201
            $method = new \ReflectionMethod($this, $getter);
1243 201
            $realName = lcfirst(substr($method->getName(), 3));
1244 201
            if ($realName !== $name) {
1245
                if ($throwException) {
1246
                    throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($this) . " has a relation named \"$realName\" instead of \"$name\".");
1247
                }
1248
1249
                return null;
1250
            }
1251
        }
1252
1253 201
        return $relation;
1254
    }
1255
1256
    /**
1257
     * Establishes the relationship between two models.
1258
     *
1259
     * The relationship is established by setting the foreign key value(s) in one model
1260
     * to be the corresponding primary key value(s) in the other model.
1261
     * The model with the foreign key will be saved into database **without** performing validation
1262
     * and **without** events/behaviors.
1263
     *
1264
     * If the relationship involves a junction table, a new row will be inserted into the
1265
     * junction table which contains the primary key values from both models.
1266
     *
1267
     * Note that this method requires that the primary key value is not null.
1268
     *
1269
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1270
     * @param ActiveRecordInterface $model the model to be linked with the current one.
1271
     * @param array $extraColumns additional column values to be saved into the junction table.
1272
     * This parameter is only meaningful for a relationship involving a junction table
1273
     * (i.e., a relation set with [[ActiveRelationTrait::via()]] or [[ActiveQuery::viaTable()]].)
1274
     * @throws InvalidCallException if the method is unable to link two models.
1275
     */
1276 9
    public function link($name, $model, $extraColumns = [])
1277
    {
1278
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1279 9
        $relation = $this->getRelation($name);
1280
1281 9
        if ($relation->via !== null) {
0 ignored issues
show
Bug introduced by
Accessing via on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1282 3
            if ($this->getIsNewRecord() || $model->getIsNewRecord()) {
1283
                throw new InvalidCallException('Unable to link models: the models being linked cannot be newly created.');
1284
            }
1285 3
            if (is_array($relation->via)) {
1286
                /* @var $viaRelation ActiveQuery */
1287 3
                list($viaName, $viaRelation) = $relation->via;
1288 3
                $viaClass = $viaRelation->modelClass;
1289
                // unset $viaName so that it can be reloaded to reflect the change
1290 3
                unset($this->_related[$viaName]);
1291
            } else {
1292
                $viaRelation = $relation->via;
1293
                $viaTable = reset($relation->via->from);
1294
            }
1295 3
            $columns = [];
1296 3
            foreach ($viaRelation->link as $a => $b) {
1297 3
                $columns[$a] = $this->$b;
1298
            }
1299 3
            foreach ($relation->link as $a => $b) {
0 ignored issues
show
Bug introduced by
Accessing link on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1300 3
                $columns[$b] = $model->$a;
1301
            }
1302 3
            foreach ($extraColumns as $k => $v) {
1303 3
                $columns[$k] = $v;
1304
            }
1305 3
            if (is_array($relation->via)) {
1306
                /* @var $viaClass ActiveRecordInterface */
1307
                /* @var $record ActiveRecordInterface */
1308 3
                $record = Yii::createObject($viaClass);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaClass does not seem to be defined for all execution paths leading up to this point.
Loading history...
1309 3
                foreach ($columns as $column => $value) {
1310 3
                    $record->$column = $value;
1311
                }
1312 3
                $record->insert(false);
1313
            } else {
1314
                /* @var $viaTable string */
1315 3
                static::getDb()->createCommand()->insert($viaTable, $columns)->execute();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaTable does not seem to be defined for all execution paths leading up to this point.
Loading history...
1316
            }
1317
        } else {
1318 9
            $p1 = $model->isPrimaryKey(array_keys($relation->link));
1319 9
            $p2 = static::isPrimaryKey(array_values($relation->link));
1320 9
            if ($p1 && $p2) {
1321
                if ($this->getIsNewRecord()) {
1322
                    if ($model->getIsNewRecord()) {
1323
                        throw new InvalidCallException('Unable to link models: at most one model can be newly created.');
1324
                    }
1325
                    $this->bindModels(array_flip($relation->link), $this, $model);
1326
                } else {
1327
                    $this->bindModels($relation->link, $model, $this);
1328
                }
1329 9
            } elseif ($p1) {
1330 3
                $this->bindModels(array_flip($relation->link), $this, $model);
1331 9
            } elseif ($p2) {
1332 9
                $this->bindModels($relation->link, $model, $this);
1333
            } else {
1334
                throw new InvalidCallException('Unable to link models: the link defining the relation does not involve any primary key.');
1335
            }
1336
        }
1337
1338
        // update lazily loaded related objects
1339 9
        if (!$relation->multiple) {
0 ignored issues
show
Bug introduced by
Accessing multiple on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1340 3
            $this->_related[$name] = $model;
1341 9
        } elseif (isset($this->_related[$name])) {
1342 9
            if ($relation->indexBy !== null) {
0 ignored issues
show
Bug introduced by
Accessing indexBy on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1343 6
                if ($relation->indexBy instanceof \Closure) {
1344 3
                    $index = call_user_func($relation->indexBy, $model);
1345
                } else {
1346 3
                    $index = $model->{$relation->indexBy};
1347
                }
1348 6
                $this->_related[$name][$index] = $model;
1349
            } else {
1350 3
                $this->_related[$name][] = $model;
1351
            }
1352
        }
1353 9
    }
1354
1355
    /**
1356
     * Destroys the relationship between two models.
1357
     *
1358
     * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
1359
     * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
1360
     *
1361
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1362
     * @param ActiveRecordInterface $model the model to be unlinked from the current one.
1363
     * You have to make sure that the model is really related with the current model as this method
1364
     * does not check this.
1365
     * @param bool $delete whether to delete the model that contains the foreign key.
1366
     * If `false`, the model's foreign key will be set `null` and saved.
1367
     * If `true`, the model containing the foreign key will be deleted.
1368
     * @throws InvalidCallException if the models cannot be unlinked
1369
     * @throws Exception
1370
     * @throws StaleObjectException
1371
     */
1372 9
    public function unlink($name, $model, $delete = false)
1373
    {
1374
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1375 9
        $relation = $this->getRelation($name);
1376
1377 9
        if ($relation->via !== null) {
0 ignored issues
show
Bug introduced by
Accessing via on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1378 9
            if (is_array($relation->via)) {
1379
                /* @var $viaRelation ActiveQuery */
1380 9
                list($viaName, $viaRelation) = $relation->via;
1381 9
                $viaClass = $viaRelation->modelClass;
1382 9
                unset($this->_related[$viaName]);
1383
            } else {
1384 3
                $viaRelation = $relation->via;
1385 3
                $viaTable = reset($relation->via->from);
1386
            }
1387 9
            $columns = [];
1388 9
            foreach ($viaRelation->link as $a => $b) {
1389 9
                $columns[$a] = $this->$b;
1390
            }
1391 9
            foreach ($relation->link as $a => $b) {
0 ignored issues
show
Bug introduced by
Accessing link on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1392 9
                $columns[$b] = $model->$a;
1393
            }
1394 9
            $nulls = [];
1395 9
            foreach (array_keys($columns) as $a) {
1396 9
                $nulls[$a] = null;
1397
            }
1398 9
            if (property_exists($viaRelation, 'on') && $viaRelation->on !== null) {
1399 6
                $columns = ['and', $columns, $viaRelation->on];
1400
            }
1401 9
            if (is_array($relation->via)) {
1402
                /* @var $viaClass ActiveRecordInterface */
1403 9
                if ($delete) {
1404 6
                    $viaClass::deleteAll($columns);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaClass does not seem to be defined for all execution paths leading up to this point.
Loading history...
1405
                } else {
1406 9
                    $viaClass::updateAll($nulls, $columns);
1407
                }
1408
            } else {
1409
                /* @var $viaTable string */
1410
                /* @var $command Command */
1411 3
                $command = static::getDb()->createCommand();
1412 3
                if ($delete) {
1413
                    $command->delete($viaTable, $columns)->execute();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaTable does not seem to be defined for all execution paths leading up to this point.
Loading history...
1414
                } else {
1415 9
                    $command->update($viaTable, $nulls, $columns)->execute();
1416
                }
1417
            }
1418
        } else {
1419 3
            $p1 = $model->isPrimaryKey(array_keys($relation->link));
1420 3
            $p2 = static::isPrimaryKey(array_values($relation->link));
1421 3
            if ($p2) {
1422 3
                if ($delete) {
1423 3
                    $model->delete();
1424
                } else {
1425 3
                    foreach ($relation->link as $a => $b) {
1426 3
                        $model->$a = null;
1427
                    }
1428 3
                    $model->save(false);
1429
                }
1430
            } elseif ($p1) {
1431
                foreach ($relation->link as $a => $b) {
1432
                    if (is_array($this->$b)) { // relation via array valued attribute
1433
                        if (($key = array_search($model->$a, $this->$b, false)) !== false) {
1434
                            $values = $this->$b;
1435
                            unset($values[$key]);
1436
                            $this->$b = array_values($values);
1437
                        }
1438
                    } else {
1439
                        $this->$b = null;
1440
                    }
1441
                }
1442
                $delete ? $this->delete() : $this->save(false);
1443
            } else {
1444
                throw new InvalidCallException('Unable to unlink models: the link does not involve any primary key.');
1445
            }
1446
        }
1447
1448 9
        if (!$relation->multiple) {
0 ignored issues
show
Bug introduced by
Accessing multiple on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1449
            unset($this->_related[$name]);
1450 9
        } elseif (isset($this->_related[$name])) {
1451
            /* @var $b ActiveRecordInterface */
1452 9
            foreach ($this->_related[$name] as $a => $b) {
1453 9
                if ($model->getPrimaryKey() === $b->getPrimaryKey()) {
1454 9
                    unset($this->_related[$name][$a]);
1455
                }
1456
            }
1457
        }
1458 9
    }
1459
1460
    /**
1461
     * Destroys the relationship in current model.
1462
     *
1463
     * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
1464
     * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
1465
     *
1466
     * Note that to destroy the relationship without removing records make sure your keys can be set to null
1467
     *
1468
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1469
     * @param bool $delete whether to delete the model that contains the foreign key.
1470
     *
1471
     * Note that the deletion will be performed using [[deleteAll()]], which will not trigger any events on the related models.
1472
     * If you need [[EVENT_BEFORE_DELETE]] or [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first
1473
     * and then call [[delete()]] on each of them.
1474
     */
1475 18
    public function unlinkAll($name, $delete = false)
1476
    {
1477
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1478 18
        $relation = $this->getRelation($name);
1479
1480 18
        if ($relation->via !== null) {
0 ignored issues
show
Bug introduced by
Accessing via on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1481 9
            if (is_array($relation->via)) {
1482
                /* @var $viaRelation ActiveQuery */
1483 6
                list($viaName, $viaRelation) = $relation->via;
1484 6
                $viaClass = $viaRelation->modelClass;
1485 6
                unset($this->_related[$viaName]);
1486
            } else {
1487 3
                $viaRelation = $relation->via;
1488 3
                $viaTable = reset($relation->via->from);
1489
            }
1490 9
            $condition = [];
1491 9
            $nulls = [];
1492 9
            foreach ($viaRelation->link as $a => $b) {
1493 9
                $nulls[$a] = null;
1494 9
                $condition[$a] = $this->$b;
1495
            }
1496 9
            if (!empty($viaRelation->where)) {
1497
                $condition = ['and', $condition, $viaRelation->where];
1498
            }
1499 9
            if (property_exists($viaRelation, 'on') && !empty($viaRelation->on)) {
1500
                $condition = ['and', $condition, $viaRelation->on];
1501
            }
1502 9
            if (is_array($relation->via)) {
1503
                /* @var $viaClass ActiveRecordInterface */
1504 6
                if ($delete) {
1505 6
                    $viaClass::deleteAll($condition);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaClass does not seem to be defined for all execution paths leading up to this point.
Loading history...
1506
                } else {
1507 6
                    $viaClass::updateAll($nulls, $condition);
1508
                }
1509
            } else {
1510
                /* @var $viaTable string */
1511
                /* @var $command Command */
1512 3
                $command = static::getDb()->createCommand();
1513 3
                if ($delete) {
1514 3
                    $command->delete($viaTable, $condition)->execute();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaTable does not seem to be defined for all execution paths leading up to this point.
Loading history...
1515
                } else {
1516 9
                    $command->update($viaTable, $nulls, $condition)->execute();
1517
                }
1518
            }
1519
        } else {
1520
            /* @var $relatedModel ActiveRecordInterface */
1521 12
            $relatedModel = $relation->modelClass;
0 ignored issues
show
Bug introduced by
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1522 12
            if (!$delete && count($relation->link) === 1 && is_array($this->{$b = reset($relation->link)})) {
0 ignored issues
show
Bug introduced by
Accessing link on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1523
                // relation via array valued attribute
1524
                $this->$b = [];
1525
                $this->save(false);
1526
            } else {
1527 12
                $nulls = [];
1528 12
                $condition = [];
1529 12
                foreach ($relation->link as $a => $b) {
1530 12
                    $nulls[$a] = null;
1531 12
                    $condition[$a] = $this->$b;
1532
                }
1533 12
                if (!empty($relation->where)) {
0 ignored issues
show
Bug introduced by
Accessing where on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1534 6
                    $condition = ['and', $condition, $relation->where];
1535
                }
1536 12
                if (property_exists($relation, 'on') && !empty($relation->on)) {
1537 3
                    $condition = ['and', $condition, $relation->on];
1538
                }
1539 12
                if ($delete) {
1540 9
                    $relatedModel::deleteAll($condition);
1541
                } else {
1542 6
                    $relatedModel::updateAll($nulls, $condition);
1543
                }
1544
            }
1545
        }
1546
1547 18
        unset($this->_related[$name]);
1548 18
    }
1549
1550
    /**
1551
     * @param array $link
1552
     * @param ActiveRecordInterface $foreignModel
1553
     * @param ActiveRecordInterface $primaryModel
1554
     * @throws InvalidCallException
1555
     */
1556 9
    private function bindModels($link, $foreignModel, $primaryModel)
1557
    {
1558 9
        foreach ($link as $fk => $pk) {
1559 9
            $value = $primaryModel->$pk;
1560 9
            if ($value === null) {
1561
                throw new InvalidCallException('Unable to link models: the primary key of ' . get_class($primaryModel) . ' is null.');
1562
            }
1563 9
            if (is_array($foreignModel->$fk)) { // relation via array valued attribute
1564
                $foreignModel->{$fk}[] = $value;
1565
            } else {
1566 9
                $foreignModel->{$fk} = $value;
1567
            }
1568
        }
1569 9
        $foreignModel->save(false);
1570 9
    }
1571
1572
    /**
1573
     * Returns a value indicating whether the given set of attributes represents the primary key for this model.
1574
     * @param array $keys the set of attributes to check
1575
     * @return bool whether the given set of attributes represents the primary key for this model
1576
     */
1577 15
    public static function isPrimaryKey($keys)
1578
    {
1579 15
        $pks = static::primaryKey();
1580 15
        if (count($keys) === count($pks)) {
1581 15
            return count(array_intersect($keys, $pks)) === count($pks);
1582
        }
1583
1584 9
        return false;
1585
    }
1586
1587
    /**
1588
     * Returns the text label for the specified attribute.
1589
     * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model.
1590
     * @param string $attribute the attribute name
1591
     * @return string the attribute label
1592
     * @see generateAttributeLabel()
1593
     * @see attributeLabels()
1594
     */
1595 52
    public function getAttributeLabel($attribute)
1596
    {
1597 52
        $labels = $this->attributeLabels();
1598 52
        if (isset($labels[$attribute])) {
1599 5
            return $labels[$attribute];
1600 48
        } elseif (strpos($attribute, '.')) {
1601
            $attributeParts = explode('.', $attribute);
1602
            $neededAttribute = array_pop($attributeParts);
1603
1604
            $relatedModel = $this;
1605
            foreach ($attributeParts as $relationName) {
1606
                if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
1607
                    $relatedModel = $relatedModel->$relationName;
1608
                } else {
1609
                    try {
1610
                        $relation = $relatedModel->getRelation($relationName);
1611
                    } catch (InvalidParamException $e) {
1612
                        return $this->generateAttributeLabel($attribute);
1613
                    }
1614
                    /* @var $modelClass ActiveRecordInterface */
1615
                    $modelClass = $relation->modelClass;
0 ignored issues
show
Bug introduced by
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1616
                    $relatedModel = $modelClass::instance();
1617
                }
1618
            }
1619
1620
            $labels = $relatedModel->attributeLabels();
1621
            if (isset($labels[$neededAttribute])) {
1622
                return $labels[$neededAttribute];
1623
            }
1624
        }
1625
1626 48
        return $this->generateAttributeLabel($attribute);
1627
    }
1628
1629
    /**
1630
     * Returns the text hint for the specified attribute.
1631
     * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model.
1632
     * @param string $attribute the attribute name
1633
     * @return string the attribute hint
1634
     * @see attributeHints()
1635
     * @since 2.0.4
1636
     */
1637
    public function getAttributeHint($attribute)
1638
    {
1639
        $hints = $this->attributeHints();
1640
        if (isset($hints[$attribute])) {
1641
            return $hints[$attribute];
1642
        } elseif (strpos($attribute, '.')) {
1643
            $attributeParts = explode('.', $attribute);
1644
            $neededAttribute = array_pop($attributeParts);
1645
1646
            $relatedModel = $this;
1647
            foreach ($attributeParts as $relationName) {
1648
                if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
1649
                    $relatedModel = $relatedModel->$relationName;
1650
                } else {
1651
                    try {
1652
                        $relation = $relatedModel->getRelation($relationName);
1653
                    } catch (InvalidParamException $e) {
1654
                        return '';
1655
                    }
1656
                    /* @var $modelClass ActiveRecordInterface */
1657
                    $modelClass = $relation->modelClass;
0 ignored issues
show
Bug introduced by
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1658
                    $relatedModel = $modelClass::instance();
1659
                }
1660
            }
1661
1662
            $hints = $relatedModel->attributeHints();
1663
            if (isset($hints[$neededAttribute])) {
1664
                return $hints[$neededAttribute];
1665
            }
1666
        }
1667
1668
        return '';
1669
    }
1670
1671
    /**
1672
     * {@inheritdoc}
1673
     *
1674
     * The default implementation returns the names of the columns whose values have been populated into this record.
1675
     */
1676 3
    public function fields()
1677
    {
1678 3
        $fields = array_keys($this->_attributes);
1679
1680 3
        return array_combine($fields, $fields);
1681
    }
1682
1683
    /**
1684
     * {@inheritdoc}
1685
     *
1686
     * The default implementation returns the names of the relations that have been populated into this record.
1687
     */
1688
    public function extraFields()
1689
    {
1690
        $fields = array_keys($this->getRelatedRecords());
1691
1692
        return array_combine($fields, $fields);
1693
    }
1694
1695
    /**
1696
     * Sets the element value at the specified offset to null.
1697
     * This method is required by the SPL interface [[\ArrayAccess]].
1698
     * It is implicitly called when you use something like `unset($model[$offset])`.
1699
     * @param mixed $offset the offset to unset element
1700
     */
1701 3
    public function offsetUnset($offset)
1702
    {
1703 3
        if (property_exists($this, $offset)) {
1704
            $this->$offset = null;
1705
        } else {
1706 3
            unset($this->$offset);
1707
        }
1708 3
    }
1709
1710
    /**
1711
     * @param mixed $newValue
1712
     * @param mixed $oldValue
1713
     * @return bool
1714
     * @since 2.0.48
1715
     */
1716 47
    private function isValueDifferent($newValue, $oldValue)
1717
    {
1718 47
        if (is_array($newValue) && is_array($oldValue) && !ArrayHelper::isAssociative($oldValue)) {
1719
            $newValue = ArrayHelper::recursiveSort($newValue);
1720
            $oldValue = ArrayHelper::recursiveSort($oldValue);
1721
        }
1722
1723 47
        return $newValue !== $oldValue;
1724
    }
1725
}
1726