GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 7c0788...400df7 )
by Robert
18:23
created

BaseActiveRecord::isValueDifferent()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 2
nop 2
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 3
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 124
            return $this->_related[$name];
295
        }
296 142
        $value = parent::__get($name);
297 133
        if ($value instanceof ActiveQueryInterface) {
298 88
            $this->setRelationDependencies($name, $value);
299 88
            return $this->_related[$name] = $value->findFor($name, $this);
300
        }
301
302 54
        return $value;
303
    }
304
305
    /**
306
     * PHP setter magic method.
307
     * This method is overridden so that AR attributes can be accessed like properties.
308
     * @param string $name property name
309
     * @param mixed $value property value
310
     */
311 294
    public function __set($name, $value)
312
    {
313 294
        if ($this->hasAttribute($name)) {
314
            if (
315 294
                !empty($this->_relationsDependencies[$name])
316 294
                && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
317
            ) {
318 15
                $this->resetDependentRelations($name);
319
            }
320 294
            $this->_attributes[$name] = $value;
321
        } else {
322 6
            parent::__set($name, $value);
323
        }
324 294
    }
325
326
    /**
327
     * Checks if a property value is null.
328
     * This method overrides the parent implementation by checking if the named attribute is `null` or not.
329
     * @param string $name the property name or the event name
330
     * @return bool whether the property value is null
331
     */
332 251
    public function __isset($name)
333
    {
334
        try {
335 251
            return $this->__get($name) !== null;
336 13
        } catch (\Exception $t) {
337 13
            return false;
338
        } catch (\Throwable $e) {
339
            return false;
340
        }
341
    }
342
343
    /**
344
     * Sets a component property to be null.
345
     * This method overrides the parent implementation by clearing
346
     * the specified attribute value.
347
     * @param string $name the property name or the event name
348
     */
349 15
    public function __unset($name)
350
    {
351 15
        if ($this->hasAttribute($name)) {
352 9
            unset($this->_attributes[$name]);
353 9
            if (!empty($this->_relationsDependencies[$name])) {
354 9
                $this->resetDependentRelations($name);
355
            }
356 6
        } elseif (array_key_exists($name, $this->_related)) {
357 6
            unset($this->_related[$name]);
358
        } elseif ($this->getRelation($name, false) === null) {
359
            parent::__unset($name);
360
        }
361 15
    }
362
363
    /**
364
     * Declares a `has-one` relation.
365
     * The declaration is returned in terms of a relational [[ActiveQuery]] instance
366
     * through which the related record can be queried and retrieved back.
367
     *
368
     * A `has-one` relation means that there is at most one related record matching
369
     * the criteria set by this relation, e.g., a customer has one country.
370
     *
371
     * For example, to declare the `country` relation for `Customer` class, we can write
372
     * the following code in the `Customer` class:
373
     *
374
     * ```php
375
     * public function getCountry()
376
     * {
377
     *     return $this->hasOne(Country::class, ['id' => 'country_id']);
378
     * }
379
     * ```
380
     *
381
     * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name
382
     * in the related class `Country`, while the 'country_id' value refers to an attribute name
383
     * in the current AR class.
384
     *
385
     * Call methods declared in [[ActiveQuery]] to further customize the relation.
386
     *
387
     * @param string $class the class name of the related record
388
     * @param array $link the primary-foreign key constraint. The keys of the array refer to
389
     * the attributes of the record associated with the `$class` model, while the values of the
390
     * array refer to the corresponding attributes in **this** AR class.
391
     * @return ActiveQueryInterface the relational query object.
392
     */
393 106
    public function hasOne($class, $link)
394
    {
395 106
        return $this->createRelationQuery($class, $link, false);
396
    }
397
398
    /**
399
     * Declares a `has-many` relation.
400
     * The declaration is returned in terms of a relational [[ActiveQuery]] instance
401
     * through which the related record can be queried and retrieved back.
402
     *
403
     * A `has-many` relation means that there are multiple related records matching
404
     * the criteria set by this relation, e.g., a customer has many orders.
405
     *
406
     * For example, to declare the `orders` relation for `Customer` class, we can write
407
     * the following code in the `Customer` class:
408
     *
409
     * ```php
410
     * public function getOrders()
411
     * {
412
     *     return $this->hasMany(Order::class, ['customer_id' => 'id']);
413
     * }
414
     * ```
415
     *
416
     * Note that in the above, the 'customer_id' key in the `$link` parameter refers to
417
     * an attribute name in the related class `Order`, while the 'id' value refers to
418
     * an attribute name in the current AR class.
419
     *
420
     * Call methods declared in [[ActiveQuery]] to further customize the relation.
421
     *
422
     * @param string $class the class name of the related record
423
     * @param array $link the primary-foreign key constraint. The keys of the array refer to
424
     * the attributes of the record associated with the `$class` model, while the values of the
425
     * array refer to the corresponding attributes in **this** AR class.
426
     * @return ActiveQueryInterface the relational query object.
427
     */
428 180
    public function hasMany($class, $link)
429
    {
430 180
        return $this->createRelationQuery($class, $link, true);
431
    }
432
433
    /**
434
     * Creates a query instance for `has-one` or `has-many` relation.
435
     * @param string $class the class name of the related record.
436
     * @param array $link the primary-foreign key constraint.
437
     * @param bool $multiple whether this query represents a relation to more than one record.
438
     * @return ActiveQueryInterface the relational query object.
439
     * @since 2.0.12
440
     * @see hasOne()
441
     * @see hasMany()
442
     */
443 235
    protected function createRelationQuery($class, $link, $multiple)
444
    {
445
        /* @var $class ActiveRecordInterface */
446
        /* @var $query ActiveQuery */
447 235
        $query = $class::find();
448 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...
449 235
        $query->link = $link;
450 235
        $query->multiple = $multiple;
451 235
        return $query;
452
    }
453
454
    /**
455
     * Populates the named relation with the related records.
456
     * Note that this method does not check if the relation exists or not.
457
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
458
     * @param ActiveRecordInterface|array|null $records the related records to be populated into the relation.
459
     * @see getRelation()
460
     */
461 150
    public function populateRelation($name, $records)
462
    {
463 150
        foreach ($this->_relationsDependencies as &$relationNames) {
464 21
            unset($relationNames[$name]);
465
        }
466
467 150
        $this->_related[$name] = $records;
468 150
    }
469
470
    /**
471
     * Check whether the named relation has been populated with records.
472
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
473
     * @return bool whether relation has been populated with records.
474
     * @see getRelation()
475
     */
476 93
    public function isRelationPopulated($name)
477
    {
478 93
        return array_key_exists($name, $this->_related);
479
    }
480
481
    /**
482
     * Returns all populated related records.
483
     * @return array an array of related records indexed by relation names.
484
     * @see getRelation()
485
     */
486 6
    public function getRelatedRecords()
487
    {
488 6
        return $this->_related;
489
    }
490
491
    /**
492
     * Returns a value indicating whether the model has an attribute with the specified name.
493
     * @param string $name the name of the attribute
494
     * @return bool whether the model has an attribute with the specified name.
495
     */
496 359
    public function hasAttribute($name)
497
    {
498 359
        return isset($this->_attributes[$name]) || in_array($name, $this->attributes(), true);
499
    }
500
501
    /**
502
     * Returns the named attribute value.
503
     * If this record is the result of a query and the attribute is not loaded,
504
     * `null` will be returned.
505
     * @param string $name the attribute name
506
     * @return mixed the attribute value. `null` if the attribute is not set or does not exist.
507
     * @see hasAttribute()
508
     */
509 4
    public function getAttribute($name)
510
    {
511 4
        return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
512
    }
513
514
    /**
515
     * Sets the named attribute value.
516
     * @param string $name the attribute name
517
     * @param mixed $value the attribute value.
518
     * @throws InvalidArgumentException if the named attribute does not exist.
519
     * @see hasAttribute()
520
     */
521 97
    public function setAttribute($name, $value)
522
    {
523 97
        if ($this->hasAttribute($name)) {
524
            if (
525 97
                !empty($this->_relationsDependencies[$name])
526 97
                && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
527
            ) {
528 6
                $this->resetDependentRelations($name);
529
            }
530 97
            $this->_attributes[$name] = $value;
531
        } else {
532
            throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
533
        }
534 97
    }
535
536
    /**
537
     * Returns the old attribute values.
538
     * @return array the old attribute values (name-value pairs)
539
     */
540
    public function getOldAttributes()
541
    {
542
        return $this->_oldAttributes === null ? [] : $this->_oldAttributes;
543
    }
544
545
    /**
546
     * Sets the old attribute values.
547
     * All existing old attribute values will be discarded.
548
     * @param array|null $values old attribute values to be set.
549
     * If set to `null` this record is considered to be [[isNewRecord|new]].
550
     */
551 105
    public function setOldAttributes($values)
552
    {
553 105
        $this->_oldAttributes = $values;
554 105
    }
555
556
    /**
557
     * Returns the old value of the named attribute.
558
     * If this record is the result of a query and the attribute is not loaded,
559
     * `null` will be returned.
560
     * @param string $name the attribute name
561
     * @return mixed the old attribute value. `null` if the attribute is not loaded before
562
     * or does not exist.
563
     * @see hasAttribute()
564
     */
565
    public function getOldAttribute($name)
566
    {
567
        return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
568
    }
569
570
    /**
571
     * Sets the old value of the named attribute.
572
     * @param string $name the attribute name
573
     * @param mixed $value the old attribute value.
574
     * @throws InvalidArgumentException if the named attribute does not exist.
575
     * @see hasAttribute()
576
     */
577 120
    public function setOldAttribute($name, $value)
578
    {
579 120
        if (isset($this->_oldAttributes[$name]) || $this->hasAttribute($name)) {
580 120
            $this->_oldAttributes[$name] = $value;
581
        } else {
582
            throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
583
        }
584 120
    }
585
586
    /**
587
     * Marks an attribute dirty.
588
     * This method may be called to force updating a record when calling [[update()]],
589
     * even if there is no change being made to the record.
590
     * @param string $name the attribute name
591
     */
592 7
    public function markAttributeDirty($name)
593
    {
594 7
        unset($this->_oldAttributes[$name]);
595 7
    }
596
597
    /**
598
     * Returns a value indicating whether the named attribute has been changed.
599
     * @param string $name the name of the attribute.
600
     * @param bool $identical whether the comparison of new and old value is made for
601
     * identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison.
602
     * This parameter is available since version 2.0.4.
603
     * @return bool whether the attribute has been changed
604
     */
605 2
    public function isAttributeChanged($name, $identical = true)
606
    {
607 2
        if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) {
608 1
            if ($identical) {
609 1
                return $this->_attributes[$name] !== $this->_oldAttributes[$name];
610
            }
611
612
            return $this->_attributes[$name] != $this->_oldAttributes[$name];
613
        }
614
615 1
        return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]);
616
    }
617
618
    /**
619
     * Returns the attribute values that have been modified since they are loaded or saved most recently.
620
     *
621
     * The comparison of new and old values is made for identical values using `===`.
622
     *
623
     * @param string[]|null $names the names of the attributes whose values may be returned if they are
624
     * changed recently. If null, [[attributes()]] will be used.
625
     * @return array the changed attribute values (name-value pairs)
626
     */
627 116
    public function getDirtyAttributes($names = null)
628
    {
629 116
        if ($names === null) {
630 113
            $names = $this->attributes();
631
        }
632 116
        $names = array_flip($names);
633 116
        $attributes = [];
634 116
        if ($this->_oldAttributes === null) {
635 102
            foreach ($this->_attributes as $name => $value) {
636 98
                if (isset($names[$name])) {
637 98
                    $attributes[$name] = $value;
638
                }
639
            }
640
        } else {
641 47
            foreach ($this->_attributes as $name => $value) {
642 47
                if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $this->isValueDifferent($value, $this->_oldAttributes[$name]))) {
643 43
                    $attributes[$name] = $value;
644
                }
645
            }
646
        }
647
648 116
        return $attributes;
649
    }
650
651
    /**
652
     * Saves the current record.
653
     *
654
     * This method will call [[insert()]] when [[isNewRecord]] is `true`, or [[update()]]
655
     * when [[isNewRecord]] is `false`.
656
     *
657
     * For example, to save a customer record:
658
     *
659
     * ```php
660
     * $customer = new Customer; // or $customer = Customer::findOne($id);
661
     * $customer->name = $name;
662
     * $customer->email = $email;
663
     * $customer->save();
664
     * ```
665
     *
666
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
667
     * before saving the record. Defaults to `true`. If the validation fails, the record
668
     * will not be saved to the database and this method will return `false`.
669
     * @param array|null $attributeNames list of attribute names that need to be saved. Defaults to null,
670
     * meaning all attributes that are loaded from DB will be saved.
671
     * @return bool whether the saving succeeded (i.e. no validation errors occurred).
672
     */
673 110
    public function save($runValidation = true, $attributeNames = null)
674
    {
675 110
        if ($this->getIsNewRecord()) {
676 96
            return $this->insert($runValidation, $attributeNames);
677
        }
678
679 31
        return $this->update($runValidation, $attributeNames) !== false;
680
    }
681
682
    /**
683
     * Saves the changes to this active record into the associated database table.
684
     *
685
     * This method performs the following steps in order:
686
     *
687
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
688
     *    returns `false`, the rest of the steps will be skipped;
689
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
690
     *    failed, the rest of the steps will be skipped;
691
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
692
     *    the rest of the steps will be skipped;
693
     * 4. save the record into database. If this fails, it will skip the rest of the steps;
694
     * 5. call [[afterSave()]];
695
     *
696
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
697
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
698
     * will be raised by the corresponding methods.
699
     *
700
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
701
     *
702
     * For example, to update a customer record:
703
     *
704
     * ```php
705
     * $customer = Customer::findOne($id);
706
     * $customer->name = $name;
707
     * $customer->email = $email;
708
     * $customer->update();
709
     * ```
710
     *
711
     * Note that it is possible the update does not affect any row in the table.
712
     * In this case, this method will return 0. For this reason, you should use the following
713
     * code to check if update() is successful or not:
714
     *
715
     * ```php
716
     * if ($customer->update() !== false) {
717
     *     // update successful
718
     * } else {
719
     *     // update failed
720
     * }
721
     * ```
722
     *
723
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
724
     * before saving the record. Defaults to `true`. If the validation fails, the record
725
     * will not be saved to the database and this method will return `false`.
726
     * @param array|null $attributeNames list of attribute names that need to be saved. Defaults to null,
727
     * meaning all attributes that are loaded from DB will be saved.
728
     * @return int|false the number of rows affected, or `false` if validation fails
729
     * or [[beforeSave()]] stops the updating process.
730
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
731
     * being updated is outdated.
732
     * @throws Exception in case update failed.
733
     */
734
    public function update($runValidation = true, $attributeNames = null)
735
    {
736
        if ($runValidation && !$this->validate($attributeNames)) {
737
            return false;
738
        }
739
740
        return $this->updateInternal($attributeNames);
741
    }
742
743
    /**
744
     * Updates the specified attributes.
745
     *
746
     * This method is a shortcut to [[update()]] when data validation is not needed
747
     * and only a small set attributes need to be updated.
748
     *
749
     * You may specify the attributes to be updated as name list or name-value pairs.
750
     * If the latter, the corresponding attribute values will be modified accordingly.
751
     * The method will then save the specified attributes into database.
752
     *
753
     * Note that this method will **not** perform data validation and will **not** trigger events.
754
     *
755
     * @param array $attributes the attributes (names or name-value pairs) to be updated
756
     * @return int the number of rows affected.
757
     */
758 7
    public function updateAttributes($attributes)
759
    {
760 7
        $attrs = [];
761 7
        foreach ($attributes as $name => $value) {
762 7
            if (is_int($name)) {
763
                $attrs[] = $value;
764
            } else {
765 7
                $this->$name = $value;
766 7
                $attrs[] = $name;
767
            }
768
        }
769
770 7
        $values = $this->getDirtyAttributes($attrs);
771 7
        if (empty($values) || $this->getIsNewRecord()) {
772 4
            return 0;
773
        }
774
775 6
        $rows = static::updateAll($values, $this->getOldPrimaryKey(true));
776
777 6
        foreach ($values as $name => $value) {
778 6
            $this->_oldAttributes[$name] = $this->_attributes[$name];
779
        }
780
781 6
        return $rows;
782
    }
783
784
    /**
785
     * @see update()
786
     * @param array|null $attributes attributes to update
787
     * @return int|false the number of rows affected, or false if [[beforeSave()]] stops the updating process.
788
     * @throws StaleObjectException
789
     */
790 41
    protected function updateInternal($attributes = null)
791
    {
792 41
        if (!$this->beforeSave(false)) {
793
            return false;
794
        }
795 41
        $values = $this->getDirtyAttributes($attributes);
796 41
        if (empty($values)) {
797 3
            $this->afterSave(false, $values);
798 3
            return 0;
799
        }
800 39
        $condition = $this->getOldPrimaryKey(true);
801 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...
802 39
        if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
803 5
            $values[$lock] = $this->$lock + 1;
804 5
            $condition[$lock] = $this->$lock;
805
        }
806
        // We do not check the return value of updateAll() because it's possible
807
        // that the UPDATE statement doesn't change anything and thus returns 0.
808 39
        $rows = static::updateAll($values, $condition);
809
810 39
        if ($lock !== null && !$rows) {
811 4
            throw new StaleObjectException('The object being updated is outdated.');
812
        }
813
814 39
        if (isset($values[$lock])) {
815 5
            $this->$lock = $values[$lock];
816
        }
817
818 39
        $changedAttributes = [];
819 39
        foreach ($values as $name => $value) {
820 39
            $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
821 39
            $this->_oldAttributes[$name] = $value;
822
        }
823 39
        $this->afterSave(false, $changedAttributes);
824
825 39
        return $rows;
826
    }
827
828
    /**
829
     * Updates one or several counter columns for the current AR object.
830
     * Note that this method differs from [[updateAllCounters()]] in that it only
831
     * saves counters for the current AR object.
832
     *
833
     * An example usage is as follows:
834
     *
835
     * ```php
836
     * $post = Post::findOne($id);
837
     * $post->updateCounters(['view_count' => 1]);
838
     * ```
839
     *
840
     * @param array $counters the counters to be updated (attribute name => increment value)
841
     * Use negative values if you want to decrement the counters.
842
     * @return bool whether the saving is successful
843
     * @see updateAllCounters()
844
     */
845 6
    public function updateCounters($counters)
846
    {
847 6
        if (static::updateAllCounters($counters, $this->getOldPrimaryKey(true)) > 0) {
848 6
            foreach ($counters as $name => $value) {
849 6
                if (!isset($this->_attributes[$name])) {
850 3
                    $this->_attributes[$name] = $value;
851
                } else {
852 3
                    $this->_attributes[$name] += $value;
853
                }
854 6
                $this->_oldAttributes[$name] = $this->_attributes[$name];
855
            }
856
857 6
            return true;
858
        }
859
860
        return false;
861
    }
862
863
    /**
864
     * Deletes the table row corresponding to this active record.
865
     *
866
     * This method performs the following steps in order:
867
     *
868
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
869
     *    rest of the steps;
870
     * 2. delete the record from the database;
871
     * 3. call [[afterDelete()]].
872
     *
873
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
874
     * will be raised by the corresponding methods.
875
     *
876
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
877
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
878
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
879
     * being deleted is outdated.
880
     * @throws Exception in case delete failed.
881
     */
882
    public function delete()
883
    {
884
        $result = false;
885
        if ($this->beforeDelete()) {
886
            // we do not check the return value of deleteAll() because it's possible
887
            // the record is already deleted in the database and thus the method will return 0
888
            $condition = $this->getOldPrimaryKey(true);
889
            $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...
890
            if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
891
                $condition[$lock] = $this->$lock;
892
            }
893
            $result = static::deleteAll($condition);
894
            if ($lock !== null && !$result) {
895
                throw new StaleObjectException('The object being deleted is outdated.');
896
            }
897
            $this->_oldAttributes = null;
898
            $this->afterDelete();
899
        }
900
901
        return $result;
902
    }
903
904
    /**
905
     * Returns a value indicating whether the current record is new.
906
     * @return bool whether the record is new and should be inserted when calling [[save()]].
907
     */
908 159
    public function getIsNewRecord()
909
    {
910 159
        return $this->_oldAttributes === null;
911
    }
912
913
    /**
914
     * Sets the value indicating whether the record is new.
915
     * @param bool $value whether the record is new and should be inserted when calling [[save()]].
916
     * @see getIsNewRecord()
917
     */
918
    public function setIsNewRecord($value)
919
    {
920
        $this->_oldAttributes = $value ? null : $this->_attributes;
921
    }
922
923
    /**
924
     * Initializes the object.
925
     * This method is called at the end of the constructor.
926
     * The default implementation will trigger an [[EVENT_INIT]] event.
927
     */
928 571
    public function init()
929
    {
930 571
        parent::init();
931 571
        $this->trigger(self::EVENT_INIT);
932 571
    }
933
934
    /**
935
     * This method is called when the AR object is created and populated with the query result.
936
     * The default implementation will trigger an [[EVENT_AFTER_FIND]] event.
937
     * When overriding this method, make sure you call the parent implementation to ensure the
938
     * event is triggered.
939
     */
940 381
    public function afterFind()
941
    {
942 381
        $this->trigger(self::EVENT_AFTER_FIND);
943 381
    }
944
945
    /**
946
     * This method is called at the beginning of inserting or updating a record.
947
     *
948
     * The default implementation will trigger an [[EVENT_BEFORE_INSERT]] event when `$insert` is `true`,
949
     * or an [[EVENT_BEFORE_UPDATE]] event if `$insert` is `false`.
950
     * When overriding this method, make sure you call the parent implementation like the following:
951
     *
952
     * ```php
953
     * public function beforeSave($insert)
954
     * {
955
     *     if (!parent::beforeSave($insert)) {
956
     *         return false;
957
     *     }
958
     *
959
     *     // ...custom code here...
960
     *     return true;
961
     * }
962
     * ```
963
     *
964
     * @param bool $insert whether this method called while inserting a record.
965
     * If `false`, it means the method is called while updating a record.
966
     * @return bool whether the insertion or updating should continue.
967
     * If `false`, the insertion or updating will be cancelled.
968
     */
969 122
    public function beforeSave($insert)
970
    {
971 122
        $event = new ModelEvent();
972 122
        $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
973
974 122
        return $event->isValid;
975
    }
976
977
    /**
978
     * This method is called at the end of inserting or updating a record.
979
     * The default implementation will trigger an [[EVENT_AFTER_INSERT]] event when `$insert` is `true`,
980
     * or an [[EVENT_AFTER_UPDATE]] event if `$insert` is `false`. The event class used is [[AfterSaveEvent]].
981
     * When overriding this method, make sure you call the parent implementation so that
982
     * the event is triggered.
983
     * @param bool $insert whether this method called while inserting a record.
984
     * If `false`, it means the method is called while updating a record.
985
     * @param array $changedAttributes The old values of attributes that had changed and were saved.
986
     * You can use this parameter to take action based on the changes made for example send an email
987
     * when the password had changed or implement audit trail that tracks all the changes.
988
     * `$changedAttributes` gives you the old attribute values while the active record (`$this`) has
989
     * already the new, updated values.
990
     *
991
     * Note that no automatic type conversion performed by default. You may use
992
     * [[\yii\behaviors\AttributeTypecastBehavior]] to facilitate attribute typecasting.
993
     * See https://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting.
994
     */
995 113
    public function afterSave($insert, $changedAttributes)
996
    {
997 113
        $this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE, new AfterSaveEvent([
998 113
            'changedAttributes' => $changedAttributes,
999
        ]));
1000 113
    }
1001
1002
    /**
1003
     * This method is invoked before deleting a record.
1004
     *
1005
     * The default implementation raises the [[EVENT_BEFORE_DELETE]] event.
1006
     * When overriding this method, make sure you call the parent implementation like the following:
1007
     *
1008
     * ```php
1009
     * public function beforeDelete()
1010
     * {
1011
     *     if (!parent::beforeDelete()) {
1012
     *         return false;
1013
     *     }
1014
     *
1015
     *     // ...custom code here...
1016
     *     return true;
1017
     * }
1018
     * ```
1019
     *
1020
     * @return bool whether the record should be deleted. Defaults to `true`.
1021
     */
1022 7
    public function beforeDelete()
1023
    {
1024 7
        $event = new ModelEvent();
1025 7
        $this->trigger(self::EVENT_BEFORE_DELETE, $event);
1026
1027 7
        return $event->isValid;
1028
    }
1029
1030
    /**
1031
     * This method is invoked after deleting a record.
1032
     * The default implementation raises the [[EVENT_AFTER_DELETE]] event.
1033
     * You may override this method to do postprocessing after the record is deleted.
1034
     * Make sure you call the parent implementation so that the event is raised properly.
1035
     */
1036 7
    public function afterDelete()
1037
    {
1038 7
        $this->trigger(self::EVENT_AFTER_DELETE);
1039 7
    }
1040
1041
    /**
1042
     * Repopulates this active record with the latest data.
1043
     *
1044
     * If the refresh is successful, an [[EVENT_AFTER_REFRESH]] event will be triggered.
1045
     * This event is available since version 2.0.8.
1046
     *
1047
     * @return bool whether the row still exists in the database. If `true`, the latest data
1048
     * will be populated to this active record. Otherwise, this record will remain unchanged.
1049
     */
1050
    public function refresh()
1051
    {
1052
        /* @var $record BaseActiveRecord */
1053
        $record = static::findOne($this->getPrimaryKey(true));
1054
        return $this->refreshInternal($record);
1055
    }
1056
1057
    /**
1058
     * Repopulates this active record with the latest data from a newly fetched instance.
1059
     * @param BaseActiveRecord $record the record to take attributes from.
1060
     * @return bool whether refresh was successful.
1061
     * @see refresh()
1062
     * @since 2.0.13
1063
     */
1064 29
    protected function refreshInternal($record)
1065
    {
1066 29
        if ($record === null) {
1067 3
            return false;
1068
        }
1069 29
        foreach ($this->attributes() as $name) {
1070 29
            $this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null;
1071
        }
1072 29
        $this->_oldAttributes = $record->_oldAttributes;
1073 29
        $this->_related = [];
1074 29
        $this->_relationsDependencies = [];
1075 29
        $this->afterRefresh();
1076
1077 29
        return true;
1078
    }
1079
1080
    /**
1081
     * This method is called when the AR object is refreshed.
1082
     * The default implementation will trigger an [[EVENT_AFTER_REFRESH]] event.
1083
     * When overriding this method, make sure you call the parent implementation to ensure the
1084
     * event is triggered.
1085
     * @since 2.0.8
1086
     */
1087 29
    public function afterRefresh()
1088
    {
1089 29
        $this->trigger(self::EVENT_AFTER_REFRESH);
1090 29
    }
1091
1092
    /**
1093
     * Returns a value indicating whether the given active record is the same as the current one.
1094
     * The comparison is made by comparing the table names and the primary key values of the two active records.
1095
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
1096
     * @param ActiveRecordInterface $record record to compare to
1097
     * @return bool whether the two active records refer to the same row in the same database table.
1098
     */
1099
    public function equals($record)
1100
    {
1101
        if ($this->getIsNewRecord() || $record->getIsNewRecord()) {
1102
            return false;
1103
        }
1104
1105
        return get_class($this) === get_class($record) && $this->getPrimaryKey() === $record->getPrimaryKey();
1106
    }
1107
1108
    /**
1109
     * Returns the primary key value(s).
1110
     * @param bool $asArray whether to return the primary key value as an array. If `true`,
1111
     * the return value will be an array with column names as keys and column values as values.
1112
     * Note that for composite primary keys, an array will always be returned regardless of this parameter value.
1113
     * @return mixed the primary key value. An array (column name => column value) is returned if the primary key
1114
     * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
1115
     * the key value is null).
1116
     */
1117 51
    public function getPrimaryKey($asArray = false)
1118
    {
1119 51
        $keys = static::primaryKey();
1120 51
        if (!$asArray && count($keys) === 1) {
1121 25
            return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null;
1122
        }
1123
1124 29
        $values = [];
1125 29
        foreach ($keys as $name) {
1126 29
            $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
1127
        }
1128
1129 29
        return $values;
1130
    }
1131
1132
    /**
1133
     * Returns the old primary key value(s).
1134
     * This refers to the primary key value that is populated into the record
1135
     * after executing a find method (e.g. find(), findOne()).
1136
     * The value remains unchanged even if the primary key attribute is manually assigned with a different value.
1137
     * @param bool $asArray whether to return the primary key value as an array. If `true`,
1138
     * the return value will be an array with column name as key and column value as value.
1139
     * If this is `false` (default), a scalar value will be returned for non-composite primary key.
1140
     * @return mixed the old primary key value. An array (column name => column value) is returned if the primary key
1141
     * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
1142
     * the key value is null).
1143
     * @throws Exception if the AR model does not have a primary key
1144
     */
1145 77
    public function getOldPrimaryKey($asArray = false)
1146
    {
1147 77
        $keys = static::primaryKey();
1148 77
        if (empty($keys)) {
1149
            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.');
1150
        }
1151 77
        if (!$asArray && count($keys) === 1) {
1152
            return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null;
1153
        }
1154
1155 77
        $values = [];
1156 77
        foreach ($keys as $name) {
1157 77
            $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
1158
        }
1159
1160 77
        return $values;
1161
    }
1162
1163
    /**
1164
     * Populates an active record object using a row of data from the database/storage.
1165
     *
1166
     * This is an internal method meant to be called to create active record objects after
1167
     * fetching data from the database. It is mainly used by [[ActiveQuery]] to populate
1168
     * the query results into active records.
1169
     *
1170
     * When calling this method manually you should call [[afterFind()]] on the created
1171
     * record to trigger the [[EVENT_AFTER_FIND|afterFind Event]].
1172
     *
1173
     * @param BaseActiveRecord $record the record to be populated. In most cases this will be an instance
1174
     * created by [[instantiate()]] beforehand.
1175
     * @param array $row attribute values (name => value)
1176
     */
1177 381
    public static function populateRecord($record, $row)
1178
    {
1179 381
        $columns = array_flip($record->attributes());
1180 381
        foreach ($row as $name => $value) {
1181 381
            if (isset($columns[$name])) {
1182 381
                $record->_attributes[$name] = $value;
1183 6
            } elseif ($record->canSetProperty($name)) {
1184 6
                $record->$name = $value;
1185
            }
1186
        }
1187 381
        $record->_oldAttributes = $record->_attributes;
1188 381
        $record->_related = [];
1189 381
        $record->_relationsDependencies = [];
1190 381
    }
1191
1192
    /**
1193
     * Creates an active record instance.
1194
     *
1195
     * This method is called together with [[populateRecord()]] by [[ActiveQuery]].
1196
     * It is not meant to be used for creating new records directly.
1197
     *
1198
     * You may override this method if the instance being created
1199
     * depends on the row data to be populated into the record.
1200
     * For example, by creating a record based on the value of a column,
1201
     * you may implement the so-called single-table inheritance mapping.
1202
     * @param array $row row data to be populated into the record.
1203
     * @return static the newly created active record
1204
     */
1205 375
    public static function instantiate($row)
1206
    {
1207 375
        return new static();
1208
    }
1209
1210
    /**
1211
     * Returns whether there is an element at the specified offset.
1212
     * This method is required by the interface [[\ArrayAccess]].
1213
     * @param mixed $offset the offset to check on
1214
     * @return bool whether there is an element at the specified offset.
1215
     */
1216
    #[\ReturnTypeWillChange]
1217 236
    public function offsetExists($offset)
1218
    {
1219 236
        return $this->__isset($offset);
1220
    }
1221
1222
    /**
1223
     * Returns the relation object with the specified name.
1224
     * A relation is defined by a getter method which returns an [[ActiveQueryInterface]] object.
1225
     * It can be declared in either the Active Record class itself or one of its behaviors.
1226
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
1227
     * @param bool $throwException whether to throw exception if the relation does not exist.
1228
     * @return ActiveQueryInterface|ActiveQuery|null the relational query object. If the relation does not exist
1229
     * and `$throwException` is `false`, `null` will be returned.
1230
     * @throws InvalidArgumentException if the named relation does not exist.
1231
     */
1232 201
    public function getRelation($name, $throwException = true)
1233
    {
1234 201
        $getter = 'get' . $name;
1235
        try {
1236
            // the relation could be defined in a behavior
1237 201
            $relation = $this->$getter();
1238
        } catch (UnknownMethodException $e) {
1239
            if ($throwException) {
1240
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e);
1241
            }
1242
1243
            return null;
1244
        }
1245 201
        if (!$relation instanceof ActiveQueryInterface) {
1246
            if ($throwException) {
1247
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".');
1248
            }
1249
1250
            return null;
1251
        }
1252
1253 201
        if (method_exists($this, $getter)) {
1254
            // relation name is case sensitive, trying to validate it when the relation is defined within this class
1255 201
            $method = new \ReflectionMethod($this, $getter);
1256 201
            $realName = lcfirst(substr($method->getName(), 3));
1257 201
            if ($realName !== $name) {
1258
                if ($throwException) {
1259
                    throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($this) . " has a relation named \"$realName\" instead of \"$name\".");
1260
                }
1261
1262
                return null;
1263
            }
1264
        }
1265
1266 201
        return $relation;
1267
    }
1268
1269
    /**
1270
     * Establishes the relationship between two models.
1271
     *
1272
     * The relationship is established by setting the foreign key value(s) in one model
1273
     * to be the corresponding primary key value(s) in the other model.
1274
     * The model with the foreign key will be saved into database **without** performing validation
1275
     * and **without** events/behaviors.
1276
     *
1277
     * If the relationship involves a junction table, a new row will be inserted into the
1278
     * junction table which contains the primary key values from both models.
1279
     *
1280
     * Note that this method requires that the primary key value is not null.
1281
     *
1282
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1283
     * @param ActiveRecordInterface $model the model to be linked with the current one.
1284
     * @param array $extraColumns additional column values to be saved into the junction table.
1285
     * This parameter is only meaningful for a relationship involving a junction table
1286
     * (i.e., a relation set with [[ActiveRelationTrait::via()]] or [[ActiveQuery::viaTable()]].)
1287
     * @throws InvalidCallException if the method is unable to link two models.
1288
     */
1289 9
    public function link($name, $model, $extraColumns = [])
1290
    {
1291
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1292 9
        $relation = $this->getRelation($name);
1293
1294 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...
1295 3
            if ($this->getIsNewRecord() || $model->getIsNewRecord()) {
1296
                throw new InvalidCallException('Unable to link models: the models being linked cannot be newly created.');
1297
            }
1298 3
            if (is_array($relation->via)) {
1299
                /* @var $viaRelation ActiveQuery */
1300 3
                list($viaName, $viaRelation) = $relation->via;
1301 3
                $viaClass = $viaRelation->modelClass;
1302
                // unset $viaName so that it can be reloaded to reflect the change
1303 3
                unset($this->_related[$viaName]);
1304
            } else {
1305
                $viaRelation = $relation->via;
1306
                $viaTable = reset($relation->via->from);
1307
            }
1308 3
            $columns = [];
1309 3
            foreach ($viaRelation->link as $a => $b) {
1310 3
                $columns[$a] = $this->$b;
1311
            }
1312 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...
1313 3
                $columns[$b] = $model->$a;
1314
            }
1315 3
            foreach ($extraColumns as $k => $v) {
1316 3
                $columns[$k] = $v;
1317
            }
1318 3
            if (is_array($relation->via)) {
1319
                /* @var $viaClass ActiveRecordInterface */
1320
                /* @var $record ActiveRecordInterface */
1321 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...
1322 3
                foreach ($columns as $column => $value) {
1323 3
                    $record->$column = $value;
1324
                }
1325 3
                $record->insert(false);
1326
            } else {
1327
                /* @var $viaTable string */
1328 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...
1329
            }
1330
        } else {
1331 9
            $p1 = $model->isPrimaryKey(array_keys($relation->link));
1332 9
            $p2 = static::isPrimaryKey(array_values($relation->link));
1333 9
            if ($p1 && $p2) {
1334
                if ($this->getIsNewRecord()) {
1335
                    if ($model->getIsNewRecord()) {
1336
                        throw new InvalidCallException('Unable to link models: at most one model can be newly created.');
1337
                    }
1338
                    $this->bindModels(array_flip($relation->link), $this, $model);
1339
                } else {
1340
                    $this->bindModels($relation->link, $model, $this);
1341
                }
1342 9
            } elseif ($p1) {
1343 3
                $this->bindModels(array_flip($relation->link), $this, $model);
1344 9
            } elseif ($p2) {
1345 9
                $this->bindModels($relation->link, $model, $this);
1346
            } else {
1347
                throw new InvalidCallException('Unable to link models: the link defining the relation does not involve any primary key.');
1348
            }
1349
        }
1350
1351
        // update lazily loaded related objects
1352 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...
1353 3
            $this->_related[$name] = $model;
1354 9
        } elseif (isset($this->_related[$name])) {
1355 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...
1356 6
                if ($relation->indexBy instanceof \Closure) {
1357 3
                    $index = call_user_func($relation->indexBy, $model);
1358
                } else {
1359 3
                    $index = $model->{$relation->indexBy};
1360
                }
1361 6
                $this->_related[$name][$index] = $model;
1362
            } else {
1363 3
                $this->_related[$name][] = $model;
1364
            }
1365
        }
1366 9
    }
1367
1368
    /**
1369
     * Destroys the relationship between two models.
1370
     *
1371
     * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
1372
     * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
1373
     *
1374
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1375
     * @param ActiveRecordInterface $model the model to be unlinked from the current one.
1376
     * You have to make sure that the model is really related with the current model as this method
1377
     * does not check this.
1378
     * @param bool $delete whether to delete the model that contains the foreign key.
1379
     * If `false`, the model's foreign key will be set `null` and saved.
1380
     * If `true`, the model containing the foreign key will be deleted.
1381
     * @throws InvalidCallException if the models cannot be unlinked
1382
     * @throws Exception
1383
     * @throws StaleObjectException
1384
     */
1385 9
    public function unlink($name, $model, $delete = false)
1386
    {
1387
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1388 9
        $relation = $this->getRelation($name);
1389
1390 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...
1391 9
            if (is_array($relation->via)) {
1392
                /* @var $viaRelation ActiveQuery */
1393 9
                list($viaName, $viaRelation) = $relation->via;
1394 9
                $viaClass = $viaRelation->modelClass;
1395 9
                unset($this->_related[$viaName]);
1396
            } else {
1397 3
                $viaRelation = $relation->via;
1398 3
                $viaTable = reset($relation->via->from);
1399
            }
1400 9
            $columns = [];
1401 9
            foreach ($viaRelation->link as $a => $b) {
1402 9
                $columns[$a] = $this->$b;
1403
            }
1404 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...
1405 9
                $columns[$b] = $model->$a;
1406
            }
1407 9
            $nulls = [];
1408 9
            foreach (array_keys($columns) as $a) {
1409 9
                $nulls[$a] = null;
1410
            }
1411 9
            if (property_exists($viaRelation, 'on') && $viaRelation->on !== null) {
1412 6
                $columns = ['and', $columns, $viaRelation->on];
1413
            }
1414 9
            if (is_array($relation->via)) {
1415
                /* @var $viaClass ActiveRecordInterface */
1416 9
                if ($delete) {
1417 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...
1418
                } else {
1419 9
                    $viaClass::updateAll($nulls, $columns);
1420
                }
1421
            } else {
1422
                /* @var $viaTable string */
1423
                /* @var $command Command */
1424 3
                $command = static::getDb()->createCommand();
1425 3
                if ($delete) {
1426
                    $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...
1427
                } else {
1428 9
                    $command->update($viaTable, $nulls, $columns)->execute();
1429
                }
1430
            }
1431
        } else {
1432 3
            $p1 = $model->isPrimaryKey(array_keys($relation->link));
1433 3
            $p2 = static::isPrimaryKey(array_values($relation->link));
1434 3
            if ($p2) {
1435 3
                if ($delete) {
1436 3
                    $model->delete();
1437
                } else {
1438 3
                    foreach ($relation->link as $a => $b) {
1439 3
                        $model->$a = null;
1440
                    }
1441 3
                    $model->save(false);
1442
                }
1443
            } elseif ($p1) {
1444
                foreach ($relation->link as $a => $b) {
1445
                    if (is_array($this->$b)) { // relation via array valued attribute
1446
                        if (($key = array_search($model->$a, $this->$b, false)) !== false) {
1447
                            $values = $this->$b;
1448
                            unset($values[$key]);
1449
                            $this->$b = array_values($values);
1450
                        }
1451
                    } else {
1452
                        $this->$b = null;
1453
                    }
1454
                }
1455
                $delete ? $this->delete() : $this->save(false);
1456
            } else {
1457
                throw new InvalidCallException('Unable to unlink models: the link does not involve any primary key.');
1458
            }
1459
        }
1460
1461 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...
1462
            unset($this->_related[$name]);
1463 9
        } elseif (isset($this->_related[$name])) {
1464
            /* @var $b ActiveRecordInterface */
1465 9
            foreach ($this->_related[$name] as $a => $b) {
1466 9
                if ($model->getPrimaryKey() === $b->getPrimaryKey()) {
1467 9
                    unset($this->_related[$name][$a]);
1468
                }
1469
            }
1470
        }
1471 9
    }
1472
1473
    /**
1474
     * Destroys the relationship in current model.
1475
     *
1476
     * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
1477
     * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
1478
     *
1479
     * Note that to destroy the relationship without removing records make sure your keys can be set to null
1480
     *
1481
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1482
     * @param bool $delete whether to delete the model that contains the foreign key.
1483
     *
1484
     * Note that the deletion will be performed using [[deleteAll()]], which will not trigger any events on the related models.
1485
     * If you need [[EVENT_BEFORE_DELETE]] or [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first
1486
     * and then call [[delete()]] on each of them.
1487
     */
1488 18
    public function unlinkAll($name, $delete = false)
1489
    {
1490
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1491 18
        $relation = $this->getRelation($name);
1492
1493 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...
1494 9
            if (is_array($relation->via)) {
1495
                /* @var $viaRelation ActiveQuery */
1496 6
                list($viaName, $viaRelation) = $relation->via;
1497 6
                $viaClass = $viaRelation->modelClass;
1498 6
                unset($this->_related[$viaName]);
1499
            } else {
1500 3
                $viaRelation = $relation->via;
1501 3
                $viaTable = reset($relation->via->from);
1502
            }
1503 9
            $condition = [];
1504 9
            $nulls = [];
1505 9
            foreach ($viaRelation->link as $a => $b) {
1506 9
                $nulls[$a] = null;
1507 9
                $condition[$a] = $this->$b;
1508
            }
1509 9
            if (!empty($viaRelation->where)) {
1510
                $condition = ['and', $condition, $viaRelation->where];
1511
            }
1512 9
            if (property_exists($viaRelation, 'on') && !empty($viaRelation->on)) {
1513
                $condition = ['and', $condition, $viaRelation->on];
1514
            }
1515 9
            if (is_array($relation->via)) {
1516
                /* @var $viaClass ActiveRecordInterface */
1517 6
                if ($delete) {
1518 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...
1519
                } else {
1520 6
                    $viaClass::updateAll($nulls, $condition);
1521
                }
1522
            } else {
1523
                /* @var $viaTable string */
1524
                /* @var $command Command */
1525 3
                $command = static::getDb()->createCommand();
1526 3
                if ($delete) {
1527 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...
1528
                } else {
1529 9
                    $command->update($viaTable, $nulls, $condition)->execute();
1530
                }
1531
            }
1532
        } else {
1533
            /* @var $relatedModel ActiveRecordInterface */
1534 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...
1535 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...
1536
                // relation via array valued attribute
1537
                $this->$b = [];
1538
                $this->save(false);
1539
            } else {
1540 12
                $nulls = [];
1541 12
                $condition = [];
1542 12
                foreach ($relation->link as $a => $b) {
1543 12
                    $nulls[$a] = null;
1544 12
                    $condition[$a] = $this->$b;
1545
                }
1546 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...
1547 6
                    $condition = ['and', $condition, $relation->where];
1548
                }
1549 12
                if (property_exists($relation, 'on') && !empty($relation->on)) {
1550 3
                    $condition = ['and', $condition, $relation->on];
1551
                }
1552 12
                if ($delete) {
1553 9
                    $relatedModel::deleteAll($condition);
1554
                } else {
1555 6
                    $relatedModel::updateAll($nulls, $condition);
1556
                }
1557
            }
1558
        }
1559
1560 18
        unset($this->_related[$name]);
1561 18
    }
1562
1563
    /**
1564
     * @param array $link
1565
     * @param ActiveRecordInterface $foreignModel
1566
     * @param ActiveRecordInterface $primaryModel
1567
     * @throws InvalidCallException
1568
     */
1569 9
    private function bindModels($link, $foreignModel, $primaryModel)
1570
    {
1571 9
        foreach ($link as $fk => $pk) {
1572 9
            $value = $primaryModel->$pk;
1573 9
            if ($value === null) {
1574
                throw new InvalidCallException('Unable to link models: the primary key of ' . get_class($primaryModel) . ' is null.');
1575
            }
1576 9
            if (is_array($foreignModel->$fk)) { // relation via array valued attribute
1577
                $foreignModel->{$fk}[] = $value;
1578
            } else {
1579 9
                $foreignModel->{$fk} = $value;
1580
            }
1581
        }
1582 9
        $foreignModel->save(false);
1583 9
    }
1584
1585
    /**
1586
     * Returns a value indicating whether the given set of attributes represents the primary key for this model.
1587
     * @param array $keys the set of attributes to check
1588
     * @return bool whether the given set of attributes represents the primary key for this model
1589
     */
1590 15
    public static function isPrimaryKey($keys)
1591
    {
1592 15
        $pks = static::primaryKey();
1593 15
        if (count($keys) === count($pks)) {
1594 15
            return count(array_intersect($keys, $pks)) === count($pks);
1595
        }
1596
1597 9
        return false;
1598
    }
1599
1600
    /**
1601
     * Returns the text label for the specified attribute.
1602
     * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model.
1603
     * @param string $attribute the attribute name
1604
     * @return string the attribute label
1605
     * @see generateAttributeLabel()
1606
     * @see attributeLabels()
1607
     */
1608 68
    public function getAttributeLabel($attribute)
1609
    {
1610 68
        $labels = $this->attributeLabels();
1611 68
        if (isset($labels[$attribute])) {
1612 10
            return $labels[$attribute];
1613 65
        } elseif (strpos($attribute, '.')) {
1614
            $attributeParts = explode('.', $attribute);
1615
            $neededAttribute = array_pop($attributeParts);
1616
1617
            $relatedModel = $this;
1618
            foreach ($attributeParts as $relationName) {
1619
                if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
1620
                    $relatedModel = $relatedModel->$relationName;
1621
                } else {
1622
                    try {
1623
                        $relation = $relatedModel->getRelation($relationName);
1624
                    } catch (InvalidParamException $e) {
1625
                        return $this->generateAttributeLabel($attribute);
1626
                    }
1627
                    /* @var $modelClass ActiveRecordInterface */
1628
                    $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...
1629
                    $relatedModel = $modelClass::instance();
1630
                }
1631
            }
1632
1633
            $labels = $relatedModel->attributeLabels();
1634
            if (isset($labels[$neededAttribute])) {
1635
                return $labels[$neededAttribute];
1636
            }
1637
        }
1638
1639 65
        return $this->generateAttributeLabel($attribute);
1640
    }
1641
1642
    /**
1643
     * Returns the text hint for the specified attribute.
1644
     * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model.
1645
     * @param string $attribute the attribute name
1646
     * @return string the attribute hint
1647
     * @see attributeHints()
1648
     * @since 2.0.4
1649
     */
1650
    public function getAttributeHint($attribute)
1651
    {
1652
        $hints = $this->attributeHints();
1653
        if (isset($hints[$attribute])) {
1654
            return $hints[$attribute];
1655
        } elseif (strpos($attribute, '.')) {
1656
            $attributeParts = explode('.', $attribute);
1657
            $neededAttribute = array_pop($attributeParts);
1658
1659
            $relatedModel = $this;
1660
            foreach ($attributeParts as $relationName) {
1661
                if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
1662
                    $relatedModel = $relatedModel->$relationName;
1663
                } else {
1664
                    try {
1665
                        $relation = $relatedModel->getRelation($relationName);
1666
                    } catch (InvalidParamException $e) {
1667
                        return '';
1668
                    }
1669
                    /* @var $modelClass ActiveRecordInterface */
1670
                    $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...
1671
                    $relatedModel = $modelClass::instance();
1672
                }
1673
            }
1674
1675
            $hints = $relatedModel->attributeHints();
1676
            if (isset($hints[$neededAttribute])) {
1677
                return $hints[$neededAttribute];
1678
            }
1679
        }
1680
1681
        return '';
1682
    }
1683
1684
    /**
1685
     * {@inheritdoc}
1686
     *
1687
     * The default implementation returns the names of the columns whose values have been populated into this record.
1688
     */
1689 3
    public function fields()
1690
    {
1691 3
        $fields = array_keys($this->_attributes);
1692
1693 3
        return array_combine($fields, $fields);
1694
    }
1695
1696
    /**
1697
     * {@inheritdoc}
1698
     *
1699
     * The default implementation returns the names of the relations that have been populated into this record.
1700
     */
1701
    public function extraFields()
1702
    {
1703
        $fields = array_keys($this->getRelatedRecords());
1704
1705
        return array_combine($fields, $fields);
1706
    }
1707
1708
    /**
1709
     * Sets the element value at the specified offset to null.
1710
     * This method is required by the SPL interface [[\ArrayAccess]].
1711
     * It is implicitly called when you use something like `unset($model[$offset])`.
1712
     * @param mixed $offset the offset to unset element
1713
     */
1714 3
    public function offsetUnset($offset)
1715
    {
1716 3
        if (property_exists($this, $offset)) {
1717
            $this->$offset = null;
1718
        } else {
1719 3
            unset($this->$offset);
1720
        }
1721 3
    }
1722
1723
    /**
1724
     * Resets dependent related models checking if their links contain specific attribute.
1725
     * @param string $attribute The changed attribute name.
1726
     */
1727 15
    private function resetDependentRelations($attribute)
1728
    {
1729 15
        foreach ($this->_relationsDependencies[$attribute] as $relation) {
1730 15
            unset($this->_related[$relation]);
1731
        }
1732 15
        unset($this->_relationsDependencies[$attribute]);
1733 15
    }
1734
1735
    /**
1736
     * Sets relation dependencies for a property
1737
     * @param string $name property name
1738
     * @param ActiveQueryInterface $relation relation instance
1739
     * @param string|null $viaRelationName intermediate relation
1740
     */
1741 88
    private function setRelationDependencies($name, $relation, $viaRelationName = null)
1742
    {
1743 88
        if (empty($relation->via) && $relation->link) {
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...
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...
1744 85
            foreach ($relation->link as $attribute) {
1745 85
                $this->_relationsDependencies[$attribute][$name] = $name;
1746 85
                if ($viaRelationName !== null) {
1747 36
                    $this->_relationsDependencies[$attribute][] = $viaRelationName;
1748
                }
1749
            }
1750 51
        } elseif ($relation->via instanceof ActiveQueryInterface) {
1751 15
            $this->setRelationDependencies($name, $relation->via);
1752 39
        } elseif (is_array($relation->via)) {
1753 36
            list($viaRelationName, $viaQuery) = $relation->via;
1754 36
            $this->setRelationDependencies($name, $viaQuery, $viaRelationName);
1755
        }
1756 88
    }
1757
1758
    /**
1759
     * @param mixed $newValue
1760
     * @param mixed $oldValue
1761
     * @return bool
1762
     * @since 2.0.48
1763
     */
1764 47
    private function isValueDifferent($newValue, $oldValue)
1765
    {
1766 47
        if (is_array($newValue) && is_array($oldValue)) {
1767 1
            $newValue = ArrayHelper::recursiveSort($newValue);
1768 1
            $oldValue = ArrayHelper::recursiveSort($oldValue);
1769
        }
1770
1771 47
        return $newValue !== $oldValue;
1772
    }
1773
}
1774