Passed
Pull Request — 2.2 (#19955)
by Wilmer
06:08
created

BaseActiveRecord::createRelationQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

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