BaseActiveRecord::unlink()   D
last analyzed

Complexity

Conditions 23
Paths 96

Size

Total Lines 83
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 552

Importance

Changes 0
Metric Value
cc 23
eloc 58
nc 96
nop 3
dl 0
loc 83
ccs 0
cts 51
cp 0
crap 552
rs 4.1666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 56
    public function __get($name)
283
    {
284 56
        if (array_key_exists($name, $this->_attributes)) {
285 53
            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 54
    public function __set($name, $value)
311
    {
312 54
        if ($this->hasAttribute($name)) {
313
            if (
314 54
                !empty($this->_relationsDependencies[$name])
315 54
                && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
316
            ) {
317
                $this->resetDependentRelations($name);
318
            }
319 54
            $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 ActiveRecordInterface $class */
445
        /** @var ActiveQuery $query */
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 56
    public function hasAttribute($name)
496
    {
497 56
        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 24
    public function setAttribute($name, $value)
521
    {
522 24
        if ($this->hasAttribute($name)) {
523
            if (
524 24
                !empty($this->_relationsDependencies[$name])
525 24
                && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
526
            ) {
527
                $this->resetDependentRelations($name);
528
            }
529 24
            $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 25
    public function setOldAttributes($values)
551
    {
552 25
        $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 25
    public function getDirtyAttributes($names = null)
638
    {
639 25
        if ($names === null) {
640 25
            $names = $this->attributes();
641
        }
642 25
        $names = array_flip($names);
643 25
        $attributes = [];
644 25
        if ($this->_oldAttributes === null) {
645 25
            foreach ($this->_attributes as $name => $value) {
646 24
                if (isset($names[$name])) {
647 24
                    $attributes[$name] = $value;
648
                }
649
            }
650
        } else {
651 14
            foreach ($this->_attributes as $name => $value) {
652 14
                if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $this->isValueDifferent($value, $this->_oldAttributes[$name]))) {
653 10
                    $attributes[$name] = $value;
654
                }
655
            }
656
        }
657
658 25
        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
     * @throws Exception in case update or insert failed.
683
     */
684 25
    public function save($runValidation = true, $attributeNames = null)
685
    {
686 25
        if ($this->getIsNewRecord()) {
687 25
            return $this->insert($runValidation, $attributeNames);
688
        }
689
690 11
        return $this->update($runValidation, $attributeNames) !== false;
691
    }
692
693
    /**
694
     * Saves the changes to this active record into the associated database table.
695
     *
696
     * This method performs the following steps in order:
697
     *
698
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
699
     *    returns `false`, the rest of the steps will be skipped;
700
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
701
     *    failed, the rest of the steps will be skipped;
702
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
703
     *    the rest of the steps will be skipped;
704
     * 4. save the record into database. If this fails, it will skip the rest of the steps;
705
     * 5. call [[afterSave()]];
706
     *
707
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
708
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
709
     * will be raised by the corresponding methods.
710
     *
711
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
712
     *
713
     * For example, to update a customer record:
714
     *
715
     * ```php
716
     * $customer = Customer::findOne($id);
717
     * $customer->name = $name;
718
     * $customer->email = $email;
719
     * $customer->update();
720
     * ```
721
     *
722
     * Note that it is possible the update does not affect any row in the table.
723
     * In this case, this method will return 0. For this reason, you should use the following
724
     * code to check if update() is successful or not:
725
     *
726
     * ```php
727
     * if ($customer->update() !== false) {
728
     *     // update successful
729
     * } else {
730
     *     // update failed
731
     * }
732
     * ```
733
     *
734
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
735
     * before saving the record. Defaults to `true`. If the validation fails, the record
736
     * will not be saved to the database and this method will return `false`.
737
     * @param array|null $attributeNames list of attribute names that need to be saved. Defaults to null,
738
     * meaning all attributes that are loaded from DB will be saved.
739
     * @return int|false the number of rows affected, or `false` if validation fails
740
     * or [[beforeSave()]] stops the updating process.
741
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
742
     * being updated is outdated.
743
     * @throws Exception in case update failed.
744
     */
745
    public function update($runValidation = true, $attributeNames = null)
746
    {
747
        if ($runValidation && !$this->validate($attributeNames)) {
748
            return false;
749
        }
750
751
        return $this->updateInternal($attributeNames);
752
    }
753
754
    /**
755
     * Updates the specified attributes.
756
     *
757
     * This method is a shortcut to [[update()]] when data validation is not needed
758
     * and only a small set attributes need to be updated.
759
     *
760
     * You may specify the attributes to be updated as name list or name-value pairs.
761
     * If the latter, the corresponding attribute values will be modified accordingly.
762
     * The method will then save the specified attributes into database.
763
     *
764
     * Note that this method will **not** perform data validation and will **not** trigger events.
765
     *
766
     * @param array $attributes the attributes (names or name-value pairs) to be updated
767
     * @return int the number of rows affected.
768
     */
769 4
    public function updateAttributes($attributes)
770
    {
771 4
        $attrs = [];
772 4
        foreach ($attributes as $name => $value) {
773 4
            if (is_int($name)) {
774
                $attrs[] = $value;
775
            } else {
776 4
                $this->$name = $value;
777 4
                $attrs[] = $name;
778
            }
779
        }
780
781 4
        $values = $this->getDirtyAttributes($attrs);
782 4
        if (empty($values) || $this->getIsNewRecord()) {
783 1
            return 0;
784
        }
785
786 3
        $rows = static::updateAll($values, $this->getOldPrimaryKey(true));
787
788 3
        foreach ($values as $name => $value) {
789 3
            $this->_oldAttributes[$name] = $this->_attributes[$name];
790
        }
791
792 3
        return $rows;
793
    }
794
795
    /**
796
     * @see update()
797
     * @param array|null $attributes attributes to update
798
     * @return int|false the number of rows affected, or false if [[beforeSave()]] stops the updating process.
799
     * @throws StaleObjectException
800
     */
801 11
    protected function updateInternal($attributes = null)
802
    {
803 11
        if (!$this->beforeSave(false)) {
804
            return false;
805
        }
806 11
        $values = $this->getDirtyAttributes($attributes);
807 11
        if (empty($values)) {
808 3
            $this->afterSave(false, $values);
809 3
            return 0;
810
        }
811 9
        $condition = $this->getOldPrimaryKey(true);
812 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...
813 9
        if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
814 2
            $values[$lock] = $this->$lock + 1;
815 2
            $condition[$lock] = $this->$lock;
816
        }
817
        // We do not check the return value of updateAll() because it's possible
818
        // that the UPDATE statement doesn't change anything and thus returns 0.
819 9
        $rows = static::updateAll($values, $condition);
820
821 9
        if ($lock !== null && !$rows) {
822 1
            throw new StaleObjectException('The object being updated is outdated.');
823
        }
824
825 9
        if (isset($values[$lock])) {
826 2
            $this->$lock = $values[$lock];
827
        }
828
829 9
        $changedAttributes = [];
830 9
        foreach ($values as $name => $value) {
831 9
            $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
832 9
            $this->_oldAttributes[$name] = $value;
833
        }
834 9
        $this->afterSave(false, $changedAttributes);
835
836 9
        return $rows;
837
    }
838
839
    /**
840
     * Updates one or several counter columns for the current AR object.
841
     * Note that this method differs from [[updateAllCounters()]] in that it only
842
     * saves counters for the current AR object.
843
     *
844
     * An example usage is as follows:
845
     *
846
     * ```php
847
     * $post = Post::findOne($id);
848
     * $post->updateCounters(['view_count' => 1]);
849
     * ```
850
     *
851
     * @param array $counters the counters to be updated (attribute name => increment value)
852
     * Use negative values if you want to decrement the counters.
853
     * @return bool whether the saving is successful
854
     * @see updateAllCounters()
855
     */
856
    public function updateCounters($counters)
857
    {
858
        if (static::updateAllCounters($counters, $this->getOldPrimaryKey(true)) > 0) {
859
            foreach ($counters as $name => $value) {
860
                if (!isset($this->_attributes[$name])) {
861
                    $this->_attributes[$name] = $value;
862
                } else {
863
                    $this->_attributes[$name] += $value;
864
                }
865
                $this->_oldAttributes[$name] = $this->_attributes[$name];
866
            }
867
868
            return true;
869
        }
870
871
        return false;
872
    }
873
874
    /**
875
     * Deletes the table row corresponding to this active record.
876
     *
877
     * This method performs the following steps in order:
878
     *
879
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
880
     *    rest of the steps;
881
     * 2. delete the record from the database;
882
     * 3. call [[afterDelete()]].
883
     *
884
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
885
     * will be raised by the corresponding methods.
886
     *
887
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
888
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
889
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
890
     * being deleted is outdated.
891
     * @throws Exception in case delete failed.
892
     */
893
    public function delete()
894
    {
895
        $result = false;
896
        if ($this->beforeDelete()) {
897
            // we do not check the return value of deleteAll() because it's possible
898
            // the record is already deleted in the database and thus the method will return 0
899
            $condition = $this->getOldPrimaryKey(true);
900
            $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...
901
            if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
902
                $condition[$lock] = $this->$lock;
903
            }
904
            $result = static::deleteAll($condition);
905
            if ($lock !== null && !$result) {
906
                throw new StaleObjectException('The object being deleted is outdated.');
907
            }
908
            $this->_oldAttributes = null;
909
            $this->afterDelete();
910
        }
911
912
        return $result;
913
    }
914
915
    /**
916
     * Returns a value indicating whether the current record is new.
917
     * @return bool whether the record is new and should be inserted when calling [[save()]].
918
     */
919 26
    public function getIsNewRecord()
920
    {
921 26
        return $this->_oldAttributes === null;
922
    }
923
924
    /**
925
     * Sets the value indicating whether the record is new.
926
     * @param bool $value whether the record is new and should be inserted when calling [[save()]].
927
     * @see getIsNewRecord()
928
     */
929
    public function setIsNewRecord($value)
930
    {
931
        $this->_oldAttributes = $value ? null : $this->_attributes;
932
    }
933
934
    /**
935
     * Initializes the object.
936
     * This method is called at the end of the constructor.
937
     * The default implementation will trigger an [[EVENT_INIT]] event.
938
     */
939 62
    public function init()
940
    {
941 62
        parent::init();
942 62
        $this->trigger(self::EVENT_INIT);
943
    }
944
945
    /**
946
     * This method is called when the AR object is created and populated with the query result.
947
     * The default implementation will trigger an [[EVENT_AFTER_FIND]] event.
948
     * When overriding this method, make sure you call the parent implementation to ensure the
949
     * event is triggered.
950
     */
951 8
    public function afterFind()
952
    {
953 8
        $this->trigger(self::EVENT_AFTER_FIND);
954
    }
955
956
    /**
957
     * This method is called at the beginning of inserting or updating a record.
958
     *
959
     * The default implementation will trigger an [[EVENT_BEFORE_INSERT]] event when `$insert` is `true`,
960
     * or an [[EVENT_BEFORE_UPDATE]] event if `$insert` is `false`.
961
     * When overriding this method, make sure you call the parent implementation like the following:
962
     *
963
     * ```php
964
     * public function beforeSave($insert)
965
     * {
966
     *     if (!parent::beforeSave($insert)) {
967
     *         return false;
968
     *     }
969
     *
970
     *     // ...custom code here...
971
     *     return true;
972
     * }
973
     * ```
974
     *
975
     * @param bool $insert whether this method called while inserting a record.
976
     * If `false`, it means the method is called while updating a record.
977
     * @return bool whether the insertion or updating should continue.
978
     * If `false`, the insertion or updating will be cancelled.
979
     */
980 34
    public function beforeSave($insert)
981
    {
982 34
        $event = new ModelEvent();
983 34
        $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
984
985 34
        return $event->isValid;
986
    }
987
988
    /**
989
     * This method is called at the end of inserting or updating a record.
990
     * The default implementation will trigger an [[EVENT_AFTER_INSERT]] event when `$insert` is `true`,
991
     * or an [[EVENT_AFTER_UPDATE]] event if `$insert` is `false`. The event class used is [[AfterSaveEvent]].
992
     * When overriding this method, make sure you call the parent implementation so that
993
     * the event is triggered.
994
     * @param bool $insert whether this method called while inserting a record.
995
     * If `false`, it means the method is called while updating a record.
996
     * @param array $changedAttributes The old values of attributes that had changed and were saved.
997
     * You can use this parameter to take action based on the changes made for example send an email
998
     * when the password had changed or implement audit trail that tracks all the changes.
999
     * `$changedAttributes` gives you the old attribute values while the active record (`$this`) has
1000
     * already the new, updated values.
1001
     *
1002
     * Note that no automatic type conversion performed by default. You may use
1003
     * [[\yii\behaviors\AttributeTypecastBehavior]] to facilitate attribute typecasting.
1004
     * See https://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting.
1005
     */
1006 25
    public function afterSave($insert, $changedAttributes)
1007
    {
1008 25
        $this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE, new AfterSaveEvent([
1009 25
            'changedAttributes' => $changedAttributes,
1010 25
        ]));
1011
    }
1012
1013
    /**
1014
     * This method is invoked before deleting a record.
1015
     *
1016
     * The default implementation raises the [[EVENT_BEFORE_DELETE]] event.
1017
     * When overriding this method, make sure you call the parent implementation like the following:
1018
     *
1019
     * ```php
1020
     * public function beforeDelete()
1021
     * {
1022
     *     if (!parent::beforeDelete()) {
1023
     *         return false;
1024
     *     }
1025
     *
1026
     *     // ...custom code here...
1027
     *     return true;
1028
     * }
1029
     * ```
1030
     *
1031
     * @return bool whether the record should be deleted. Defaults to `true`.
1032
     */
1033 1
    public function beforeDelete()
1034
    {
1035 1
        $event = new ModelEvent();
1036 1
        $this->trigger(self::EVENT_BEFORE_DELETE, $event);
1037
1038 1
        return $event->isValid;
1039
    }
1040
1041
    /**
1042
     * This method is invoked after deleting a record.
1043
     * The default implementation raises the [[EVENT_AFTER_DELETE]] event.
1044
     * You may override this method to do postprocessing after the record is deleted.
1045
     * Make sure you call the parent implementation so that the event is raised properly.
1046
     */
1047 1
    public function afterDelete()
1048
    {
1049 1
        $this->trigger(self::EVENT_AFTER_DELETE);
1050
    }
1051
1052
    /**
1053
     * Repopulates this active record with the latest data.
1054
     *
1055
     * If the refresh is successful, an [[EVENT_AFTER_REFRESH]] event will be triggered.
1056
     * This event is available since version 2.0.8.
1057
     *
1058
     * @return bool whether the row still exists in the database. If `true`, the latest data
1059
     * will be populated to this active record. Otherwise, this record will remain unchanged.
1060
     */
1061
    public function refresh()
1062
    {
1063
        /** @var self $record */
1064
        $record = static::findOne($this->getPrimaryKey(true));
1065
        return $this->refreshInternal($record);
1066
    }
1067
1068
    /**
1069
     * Repopulates this active record with the latest data from a newly fetched instance.
1070
     * @param BaseActiveRecord $record the record to take attributes from.
1071
     * @return bool whether refresh was successful.
1072
     * @see refresh()
1073
     * @since 2.0.13
1074
     */
1075 4
    protected function refreshInternal($record)
1076
    {
1077 4
        if ($record === null) {
1078
            return false;
1079
        }
1080 4
        foreach ($this->attributes() as $name) {
1081 4
            $this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null;
1082
        }
1083 4
        $this->_oldAttributes = $record->_oldAttributes;
1084 4
        $this->_related = [];
1085 4
        $this->_relationsDependencies = [];
1086 4
        $this->afterRefresh();
1087
1088 4
        return true;
1089
    }
1090
1091
    /**
1092
     * This method is called when the AR object is refreshed.
1093
     * The default implementation will trigger an [[EVENT_AFTER_REFRESH]] event.
1094
     * When overriding this method, make sure you call the parent implementation to ensure the
1095
     * event is triggered.
1096
     * @since 2.0.8
1097
     */
1098 4
    public function afterRefresh()
1099
    {
1100 4
        $this->trigger(self::EVENT_AFTER_REFRESH);
1101
    }
1102
1103
    /**
1104
     * Returns a value indicating whether the given active record is the same as the current one.
1105
     * The comparison is made by comparing the table names and the primary key values of the two active records.
1106
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
1107
     * @param ActiveRecordInterface $record record to compare to
1108
     * @return bool whether the two active records refer to the same row in the same database table.
1109
     */
1110
    public function equals($record)
1111
    {
1112
        if ($this->getIsNewRecord() || $record->getIsNewRecord()) {
1113
            return false;
1114
        }
1115
1116
        return get_class($this) === get_class($record) && $this->getPrimaryKey() === $record->getPrimaryKey();
1117
    }
1118
1119
    /**
1120
     * Returns the primary key value(s).
1121
     * @param bool $asArray whether to return the primary key value as an array. If `true`,
1122
     * the return value will be an array with column names as keys and column values as values.
1123
     * Note that for composite primary keys, an array will always be returned regardless of this parameter value.
1124
     * @return mixed the primary key value. An array (column name => column value) is returned if the primary key
1125
     * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
1126
     * the key value is null).
1127
     */
1128 4
    public function getPrimaryKey($asArray = false)
1129
    {
1130 4
        $keys = static::primaryKey();
1131 4
        if (!$asArray && count($keys) === 1) {
1132
            return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null;
1133
        }
1134
1135 4
        $values = [];
1136 4
        foreach ($keys as $name) {
1137 4
            $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
1138
        }
1139
1140 4
        return $values;
1141
    }
1142
1143
    /**
1144
     * Returns the old primary key value(s).
1145
     * This refers to the primary key value that is populated into the record
1146
     * after executing a find method (e.g. find(), findOne()).
1147
     * The value remains unchanged even if the primary key attribute is manually assigned with a different value.
1148
     * @param bool $asArray whether to return the primary key value as an array. If `true`,
1149
     * the return value will be an array with column name as key and column value as value.
1150
     * If this is `false` (default), a scalar value will be returned for non-composite primary key.
1151
     * @return mixed the old primary key value. An array (column name => column value) is returned if the primary key
1152
     * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
1153
     * the key value is null).
1154
     * @throws Exception if the AR model does not have a primary key
1155
     */
1156 10
    public function getOldPrimaryKey($asArray = false)
1157
    {
1158 10
        $keys = static::primaryKey();
1159 10
        if (empty($keys)) {
1160
            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.');
1161
        }
1162 10
        if (!$asArray && count($keys) === 1) {
1163
            return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null;
1164
        }
1165
1166 10
        $values = [];
1167 10
        foreach ($keys as $name) {
1168 10
            $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
1169
        }
1170
1171 10
        return $values;
1172
    }
1173
1174
    /**
1175
     * Populates an active record object using a row of data from the database/storage.
1176
     *
1177
     * This is an internal method meant to be called to create active record objects after
1178
     * fetching data from the database. It is mainly used by [[ActiveQuery]] to populate
1179
     * the query results into active records.
1180
     *
1181
     * When calling this method manually you should call [[afterFind()]] on the created
1182
     * record to trigger the [[EVENT_AFTER_FIND|afterFind Event]].
1183
     *
1184
     * @param BaseActiveRecord $record the record to be populated. In most cases this will be an instance
1185
     * created by [[instantiate()]] beforehand.
1186
     * @param array $row attribute values (name => value)
1187
     */
1188 8
    public static function populateRecord($record, $row)
1189
    {
1190 8
        $columns = array_flip($record->attributes());
1191 8
        foreach ($row as $name => $value) {
1192 8
            if (isset($columns[$name])) {
1193 8
                $record->_attributes[$name] = $value;
1194
            } elseif ($record->canSetProperty($name)) {
1195
                $record->$name = $value;
1196
            }
1197
        }
1198 8
        $record->_oldAttributes = $record->_attributes;
1199 8
        $record->_related = [];
1200 8
        $record->_relationsDependencies = [];
1201
    }
1202
1203
    /**
1204
     * Creates an active record instance.
1205
     *
1206
     * This method is called together with [[populateRecord()]] by [[ActiveQuery]].
1207
     * It is not meant to be used for creating new records directly.
1208
     *
1209
     * You may override this method if the instance being created
1210
     * depends on the row data to be populated into the record.
1211
     * For example, by creating a record based on the value of a column,
1212
     * you may implement the so-called single-table inheritance mapping.
1213
     * @param array $row row data to be populated into the record.
1214
     * @return static the newly created active record
1215
     */
1216 8
    public static function instantiate($row)
1217
    {
1218 8
        return new static();
1219
    }
1220
1221
    /**
1222
     * Returns whether there is an element at the specified offset.
1223
     * This method is required by the interface [[\ArrayAccess]].
1224
     * @param mixed $offset the offset to check on
1225
     * @return bool whether there is an element at the specified offset.
1226
     */
1227 8
    #[\ReturnTypeWillChange]
1228
    public function offsetExists($offset)
1229
    {
1230 8
        return $this->__isset($offset);
1231
    }
1232
1233
    /**
1234
     * Returns the relation object with the specified name.
1235
     * A relation is defined by a getter method which returns an [[ActiveQueryInterface]] object.
1236
     * It can be declared in either the Active Record class itself or one of its behaviors.
1237
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
1238
     * @param bool $throwException whether to throw exception if the relation does not exist.
1239
     * @return ActiveQueryInterface|ActiveQuery|null the relational query object. If the relation does not exist
1240
     * and `$throwException` is `false`, `null` will be returned.
1241
     * @throws InvalidArgumentException if the named relation does not exist.
1242
     */
1243
    public function getRelation($name, $throwException = true)
1244
    {
1245
        $getter = 'get' . $name;
1246
        try {
1247
            // the relation could be defined in a behavior
1248
            $relation = $this->$getter();
1249
        } catch (UnknownMethodException $e) {
1250
            if ($throwException) {
1251
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e);
1252
            }
1253
1254
            return null;
1255
        }
1256
        if (!$relation instanceof ActiveQueryInterface) {
1257
            if ($throwException) {
1258
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".');
1259
            }
1260
1261
            return null;
1262
        }
1263
1264
        if (method_exists($this, $getter)) {
1265
            // relation name is case sensitive, trying to validate it when the relation is defined within this class
1266
            $method = new \ReflectionMethod($this, $getter);
1267
            $realName = lcfirst(substr($method->getName(), 3));
1268
            if ($realName !== $name) {
1269
                if ($throwException) {
1270
                    throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($this) . " has a relation named \"$realName\" instead of \"$name\".");
1271
                }
1272
1273
                return null;
1274
            }
1275
        }
1276
1277
        return $relation;
1278
    }
1279
1280
    /**
1281
     * Establishes the relationship between two models.
1282
     *
1283
     * The relationship is established by setting the foreign key value(s) in one model
1284
     * to be the corresponding primary key value(s) in the other model.
1285
     * The model with the foreign key will be saved into database **without** performing validation
1286
     * and **without** events/behaviors.
1287
     *
1288
     * If the relationship involves a junction table, a new row will be inserted into the
1289
     * junction table which contains the primary key values from both models.
1290
     *
1291
     * Note that this method requires that the primary key value is not null.
1292
     *
1293
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1294
     * @param ActiveRecordInterface $model the model to be linked with the current one.
1295
     * @param array $extraColumns additional column values to be saved into the junction table.
1296
     * This parameter is only meaningful for a relationship involving a junction table
1297
     * (i.e., a relation set with [[ActiveRelationTrait::via()]] or [[ActiveQuery::viaTable()]].)
1298
     * @throws InvalidCallException if the method is unable to link two models.
1299
     */
1300
    public function link($name, $model, $extraColumns = [])
1301
    {
1302
        /** @var ActiveQueryInterface|ActiveQuery $relation */
1303
        $relation = $this->getRelation($name);
1304
1305
        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...
1306
            if ($this->getIsNewRecord() || $model->getIsNewRecord()) {
1307
                throw new InvalidCallException('Unable to link models: the models being linked cannot be newly created.');
1308
            }
1309
            if (is_array($relation->via)) {
1310
                /** @var ActiveQuery $viaRelation */
1311
                list($viaName, $viaRelation) = $relation->via;
1312
                $viaClass = $viaRelation->modelClass;
1313
                // unset $viaName so that it can be reloaded to reflect the change
1314
                unset($this->_related[$viaName]);
1315
            } else {
1316
                $viaRelation = $relation->via;
1317
                $viaTable = reset($relation->via->from);
1318
            }
1319
            $columns = [];
1320
            foreach ($viaRelation->link as $a => $b) {
1321
                $columns[$a] = $this->$b;
1322
            }
1323
            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...
1324
                $columns[$b] = $model->$a;
1325
            }
1326
            foreach ($extraColumns as $k => $v) {
1327
                $columns[$k] = $v;
1328
            }
1329
            if (is_array($relation->via)) {
1330
                /** @var ActiveRecordInterface $viaClass */
1331
                /** @var ActiveRecordInterface $record */
1332
                $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...
1333
                foreach ($columns as $column => $value) {
1334
                    $record->$column = $value;
1335
                }
1336
                $record->insert(false);
1337
            } else {
1338
                /** @var string $viaTable */
1339
                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...
1340
            }
1341
        } else {
1342
            $p1 = $model->isPrimaryKey(array_keys($relation->link));
1343
            $p2 = static::isPrimaryKey(array_values($relation->link));
1344
            if ($p1 && $p2) {
1345
                if ($this->getIsNewRecord()) {
1346
                    if ($model->getIsNewRecord()) {
1347
                        throw new InvalidCallException('Unable to link models: at most one model can be newly created.');
1348
                    }
1349
                    $this->bindModels(array_flip($relation->link), $this, $model);
1350
                } else {
1351
                    $this->bindModels($relation->link, $model, $this);
1352
                }
1353
            } elseif ($p1) {
1354
                $this->bindModels(array_flip($relation->link), $this, $model);
1355
            } elseif ($p2) {
1356
                $this->bindModels($relation->link, $model, $this);
1357
            } else {
1358
                throw new InvalidCallException('Unable to link models: the link defining the relation does not involve any primary key.');
1359
            }
1360
        }
1361
1362
        // update lazily loaded related objects
1363
        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...
1364
            $this->_related[$name] = $model;
1365
        } elseif (isset($this->_related[$name])) {
1366
            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...
1367
                if ($relation->indexBy instanceof \Closure) {
1368
                    $index = call_user_func($relation->indexBy, $model);
1369
                } else {
1370
                    $index = $model->{$relation->indexBy};
1371
                }
1372
                $this->_related[$name][$index] = $model;
1373
            } else {
1374
                $this->_related[$name][] = $model;
1375
            }
1376
        }
1377
    }
1378
1379
    /**
1380
     * Destroys the relationship between two models.
1381
     *
1382
     * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
1383
     * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
1384
     *
1385
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1386
     * @param ActiveRecordInterface $model the model to be unlinked from the current one.
1387
     * You have to make sure that the model is really related with the current model as this method
1388
     * does not check this.
1389
     * @param bool $delete whether to delete the model that contains the foreign key.
1390
     * If `false`, the model's foreign key will be set `null` and saved.
1391
     * If `true`, the model containing the foreign key will be deleted.
1392
     * @throws InvalidCallException if the models cannot be unlinked
1393
     * @throws Exception
1394
     * @throws StaleObjectException
1395
     */
1396
    public function unlink($name, $model, $delete = false)
1397
    {
1398
        /** @var ActiveQueryInterface|ActiveQuery $relation */
1399
        $relation = $this->getRelation($name);
1400
1401
        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...
1402
            if (is_array($relation->via)) {
1403
                /** @var ActiveQuery $viaRelation */
1404
                list($viaName, $viaRelation) = $relation->via;
1405
                $viaClass = $viaRelation->modelClass;
1406
                unset($this->_related[$viaName]);
1407
            } else {
1408
                $viaRelation = $relation->via;
1409
                $viaTable = reset($relation->via->from);
1410
            }
1411
            $columns = [];
1412
            foreach ($viaRelation->link as $a => $b) {
1413
                $columns[$a] = $this->$b;
1414
            }
1415
            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...
1416
                $columns[$b] = $model->$a;
1417
            }
1418
            $nulls = [];
1419
            foreach (array_keys($columns) as $a) {
1420
                $nulls[$a] = null;
1421
            }
1422
            if (property_exists($viaRelation, 'on') && $viaRelation->on !== null) {
1423
                $columns = ['and', $columns, $viaRelation->on];
1424
            }
1425
            if (is_array($relation->via)) {
1426
                /** @var ActiveRecordInterface $viaClass */
1427
                if ($delete) {
1428
                    $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...
1429
                } else {
1430
                    $viaClass::updateAll($nulls, $columns);
1431
                }
1432
            } else {
1433
                /** @var string $viaTable */
1434
                /** @var Command $command */
1435
                $command = static::getDb()->createCommand();
1436
                if ($delete) {
1437
                    $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...
1438
                } else {
1439
                    $command->update($viaTable, $nulls, $columns)->execute();
1440
                }
1441
            }
1442
        } else {
1443
            $p1 = $model->isPrimaryKey(array_keys($relation->link));
1444
            $p2 = static::isPrimaryKey(array_values($relation->link));
1445
            if ($p2) {
1446
                if ($delete) {
1447
                    $model->delete();
1448
                } else {
1449
                    foreach ($relation->link as $a => $b) {
1450
                        $model->$a = null;
1451
                    }
1452
                    $model->save(false);
1453
                }
1454
            } elseif ($p1) {
1455
                foreach ($relation->link as $a => $b) {
1456
                    if (is_array($this->$b)) { // relation via array valued attribute
1457
                        if (($key = array_search($model->$a, $this->$b, false)) !== false) {
1458
                            $values = $this->$b;
1459
                            unset($values[$key]);
1460
                            $this->$b = array_values($values);
1461
                        }
1462
                    } else {
1463
                        $this->$b = null;
1464
                    }
1465
                }
1466
                $delete ? $this->delete() : $this->save(false);
1467
            } else {
1468
                throw new InvalidCallException('Unable to unlink models: the link does not involve any primary key.');
1469
            }
1470
        }
1471
1472
        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...
1473
            unset($this->_related[$name]);
1474
        } elseif (isset($this->_related[$name])) {
1475
            /** @var ActiveRecordInterface $b */
1476
            foreach ($this->_related[$name] as $a => $b) {
1477
                if ($model->getPrimaryKey() === $b->getPrimaryKey()) {
1478
                    unset($this->_related[$name][$a]);
1479
                }
1480
            }
1481
        }
1482
    }
1483
1484
    /**
1485
     * Destroys the relationship in current model.
1486
     *
1487
     * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
1488
     * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
1489
     *
1490
     * Note that to destroy the relationship without removing records make sure your keys can be set to null
1491
     *
1492
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1493
     * @param bool $delete whether to delete the model that contains the foreign key.
1494
     *
1495
     * Note that the deletion will be performed using [[deleteAll()]], which will not trigger any events on the related models.
1496
     * If you need [[EVENT_BEFORE_DELETE]] or [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first
1497
     * and then call [[delete()]] on each of them.
1498
     */
1499
    public function unlinkAll($name, $delete = false)
1500
    {
1501
        /** @var ActiveQueryInterface|ActiveQuery $relation */
1502
        $relation = $this->getRelation($name);
1503
1504
        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...
1505
            if (is_array($relation->via)) {
1506
                /** @var ActiveQuery $viaRelation */
1507
                list($viaName, $viaRelation) = $relation->via;
1508
                $viaClass = $viaRelation->modelClass;
1509
                unset($this->_related[$viaName]);
1510
            } else {
1511
                $viaRelation = $relation->via;
1512
                $viaTable = reset($relation->via->from);
1513
            }
1514
            $condition = [];
1515
            $nulls = [];
1516
            foreach ($viaRelation->link as $a => $b) {
1517
                $nulls[$a] = null;
1518
                $condition[$a] = $this->$b;
1519
            }
1520
            if (!empty($viaRelation->where)) {
1521
                $condition = ['and', $condition, $viaRelation->where];
1522
            }
1523
            if (property_exists($viaRelation, 'on') && !empty($viaRelation->on)) {
1524
                $condition = ['and', $condition, $viaRelation->on];
1525
            }
1526
            if (is_array($relation->via)) {
1527
                /** @var ActiveRecordInterface $viaClass */
1528
                if ($delete) {
1529
                    $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...
1530
                } else {
1531
                    $viaClass::updateAll($nulls, $condition);
1532
                }
1533
            } else {
1534
                /** @var string $viaTable */
1535
                /** @var Command $command */
1536
                $command = static::getDb()->createCommand();
1537
                if ($delete) {
1538
                    $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...
1539
                } else {
1540
                    $command->update($viaTable, $nulls, $condition)->execute();
1541
                }
1542
            }
1543
        } else {
1544
            /** @var ActiveRecordInterface $relatedModel */
1545
            $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...
1546
            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...
1547
                // relation via array valued attribute
1548
                $this->$b = [];
1549
                $this->save(false);
1550
            } else {
1551
                $nulls = [];
1552
                $condition = [];
1553
                foreach ($relation->link as $a => $b) {
1554
                    $nulls[$a] = null;
1555
                    $condition[$a] = $this->$b;
1556
                }
1557
                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...
1558
                    $condition = ['and', $condition, $relation->where];
1559
                }
1560
                if (property_exists($relation, 'on') && !empty($relation->on)) {
1561
                    $condition = ['and', $condition, $relation->on];
1562
                }
1563
                if ($delete) {
1564
                    $relatedModel::deleteAll($condition);
1565
                } else {
1566
                    $relatedModel::updateAll($nulls, $condition);
1567
                }
1568
            }
1569
        }
1570
1571
        unset($this->_related[$name]);
1572
    }
1573
1574
    /**
1575
     * @param array $link
1576
     * @param ActiveRecordInterface $foreignModel
1577
     * @param ActiveRecordInterface $primaryModel
1578
     * @throws InvalidCallException
1579
     */
1580
    private function bindModels($link, $foreignModel, $primaryModel)
1581
    {
1582
        foreach ($link as $fk => $pk) {
1583
            $value = $primaryModel->$pk;
1584
            if ($value === null) {
1585
                throw new InvalidCallException('Unable to link models: the primary key of ' . get_class($primaryModel) . ' is null.');
1586
            }
1587
            if (is_array($foreignModel->$fk)) { // relation via array valued attribute
1588
                $foreignModel->{$fk}[] = $value;
1589
            } else {
1590
                $foreignModel->{$fk} = $value;
1591
            }
1592
        }
1593
        $foreignModel->save(false);
1594
    }
1595
1596
    /**
1597
     * Returns a value indicating whether the given set of attributes represents the primary key for this model.
1598
     * @param array $keys the set of attributes to check
1599
     * @return bool whether the given set of attributes represents the primary key for this model
1600
     */
1601
    public static function isPrimaryKey($keys)
1602
    {
1603
        $pks = static::primaryKey();
1604
        if (count($keys) === count($pks)) {
1605
            return count(array_intersect($keys, $pks)) === count($pks);
1606
        }
1607
1608
        return false;
1609
    }
1610
1611
    /**
1612
     * Returns the text label for the specified attribute.
1613
     * 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.
1614
     * For example, if the attribute is specified as 'relatedModel1.relatedModel2.attr' the function will return the first label definition it can find
1615
     * in the following order:
1616
     * - the label for 'relatedModel1.relatedModel2.attr' defined in [[attributeLabels()]] of this model;
1617
     * - the label for 'relatedModel2.attr' defined in related model represented by relation 'relatedModel1' of this model;
1618
     * - the label for 'attr' defined in related model represented by relation 'relatedModel2' of relation 'relatedModel1'.
1619
     *   If no label definition was found then the value of $this->generateAttributeLabel('relatedModel1.relatedModel2.attr') will be returned.
1620
     * @param string $attribute the attribute name
1621
     * @return string the attribute label
1622
     * @see attributeLabels()
1623
     * @see generateAttributeLabel()
1624
     */
1625 4
    public function getAttributeLabel($attribute)
1626
    {
1627 4
        $model = $this;
1628 4
        $modelAttribute = $attribute;
1629
        for (;;) {
1630 4
            $labels = $model->attributeLabels();
1631 4
            if (isset($labels[$modelAttribute])) {
1632 2
                return $labels[$modelAttribute];
1633
            }
1634
1635 2
            $parts = explode('.', $modelAttribute, 2);
1636 2
            if (count($parts) < 2) {
1637 2
                break;
1638
            }
1639
1640
            list ($relationName, $modelAttribute) = $parts;
1641
1642
            if ($model->isRelationPopulated($relationName) && $model->$relationName instanceof self) {
1643
                $model = $model->$relationName;
1644
            } else {
1645
                try {
1646
                    $relation = $model->getRelation($relationName);
1647
                } catch (InvalidArgumentException $e) {
1648
                    break;
1649
                }
1650
                /** @var ActiveRecordInterface $modelClass */
1651
                $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...
1652 4
                $model = $modelClass::instance();
1653
            }
1654
        }
1655
1656 2
        return $this->generateAttributeLabel($attribute);
1657
    }
1658
1659
    /**
1660
     * Returns the text hint for the specified attribute.
1661
     * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model.
1662
     * @param string $attribute the attribute name
1663
     * @return string the attribute hint
1664
     * @see attributeHints()
1665
     * @since 2.0.4
1666
     */
1667
    public function getAttributeHint($attribute)
1668
    {
1669
        $hints = $this->attributeHints();
1670
        if (isset($hints[$attribute])) {
1671
            return $hints[$attribute];
1672
        } elseif (strpos($attribute, '.')) {
1673
            $attributeParts = explode('.', $attribute);
1674
            $neededAttribute = array_pop($attributeParts);
1675
1676
            $relatedModel = $this;
1677
            foreach ($attributeParts as $relationName) {
1678
                if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
1679
                    $relatedModel = $relatedModel->$relationName;
1680
                } else {
1681
                    try {
1682
                        $relation = $relatedModel->getRelation($relationName);
1683
                    } catch (InvalidArgumentException $e) {
1684
                        return '';
1685
                    }
1686
                    /** @var ActiveRecordInterface $modelClass */
1687
                    $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...
1688
                    $relatedModel = $modelClass::instance();
1689
                }
1690
            }
1691
1692
            $hints = $relatedModel->attributeHints();
1693
            if (isset($hints[$neededAttribute])) {
1694
                return $hints[$neededAttribute];
1695
            }
1696
        }
1697
1698
        return '';
1699
    }
1700
1701
    /**
1702
     * {@inheritdoc}
1703
     *
1704
     * The default implementation returns the names of the columns whose values have been populated into this record.
1705
     */
1706
    public function fields()
1707
    {
1708
        $fields = array_keys($this->_attributes);
1709
1710
        return array_combine($fields, $fields);
1711
    }
1712
1713
    /**
1714
     * {@inheritdoc}
1715
     *
1716
     * The default implementation returns the names of the relations that have been populated into this record.
1717
     */
1718
    public function extraFields()
1719
    {
1720
        $fields = array_keys($this->getRelatedRecords());
1721
1722
        return array_combine($fields, $fields);
1723
    }
1724
1725
    /**
1726
     * Sets the element value at the specified offset to null.
1727
     * This method is required by the SPL interface [[\ArrayAccess]].
1728
     * It is implicitly called when you use something like `unset($model[$offset])`.
1729
     * @param mixed $offset the offset to unset element
1730
     */
1731
    public function offsetUnset($offset)
1732
    {
1733
        if (property_exists($this, $offset)) {
1734
            $this->$offset = null;
1735
        } else {
1736
            unset($this->$offset);
1737
        }
1738
    }
1739
1740
    /**
1741
     * Resets dependent related models checking if their links contain specific attribute.
1742
     * @param string $attribute The changed attribute name.
1743
     */
1744
    private function resetDependentRelations($attribute)
1745
    {
1746
        foreach ($this->_relationsDependencies[$attribute] as $relation) {
1747
            unset($this->_related[$relation]);
1748
        }
1749
        unset($this->_relationsDependencies[$attribute]);
1750
    }
1751
1752
    /**
1753
     * Sets relation dependencies for a property
1754
     * @param string $name property name
1755
     * @param ActiveQueryInterface $relation relation instance
1756
     * @param string|null $viaRelationName intermediate relation
1757
     */
1758 1
    private function setRelationDependencies($name, $relation, $viaRelationName = null)
1759
    {
1760 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...
1761 1
            foreach ($relation->link as $attribute) {
1762 1
                $this->_relationsDependencies[$attribute][$name] = $name;
1763 1
                if ($viaRelationName !== null) {
1764
                    $this->_relationsDependencies[$attribute][] = $viaRelationName;
1765
                }
1766
            }
1767
        } elseif ($relation->via instanceof ActiveQueryInterface) {
1768
            $this->setRelationDependencies($name, $relation->via);
1769
        } elseif (is_array($relation->via)) {
1770
            list($viaRelationName, $viaQuery) = $relation->via;
1771
            $this->setRelationDependencies($name, $viaQuery, $viaRelationName);
1772
        }
1773
    }
1774
1775
    /**
1776
     * @param mixed $newValue
1777
     * @param mixed $oldValue
1778
     * @return bool
1779
     * @since 2.0.48
1780
     */
1781 14
    private function isValueDifferent($newValue, $oldValue)
1782
    {
1783 14
        if (is_array($newValue) && is_array($oldValue)) {
1784
            // Only sort associative arrays
1785
            $sorter = function (&$array) {
1786
                if (ArrayHelper::isAssociative($array)) {
1787
                    ksort($array);
1788
                }
1789
            };
1790
            $newValue = ArrayHelper::recursiveSort($newValue, $sorter);
1791
            $oldValue = ArrayHelper::recursiveSort($oldValue, $sorter);
1792
        }
1793
1794 14
        return $newValue !== $oldValue;
1795
    }
1796
1797
    /**
1798
     * Eager loads related models for the already loaded primary models.
1799
     *
1800
     * Helps to reduce the number of queries performed against database if some related models are only used
1801
     * when a specific condition is met. For example:
1802
     *
1803
     * ```php
1804
     * $customers = Customer::find()->where(['country_id' => 123])->all();
1805
     * if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
1806
     *     Customer::loadRelationsFor($customers, 'orders.items');
1807
     * }
1808
     * ```
1809
     *
1810
     * @param array|ActiveRecordInterface[] $models array of primary models. Each model should have the same type and can be:
1811
     * - an active record instance;
1812
     * - active record instance represented by array (i.e. active record was loaded using [[ActiveQuery::asArray()]]).
1813
     * @param string|array $relationNames the names of the relations of primary models to be loaded from database. See [[ActiveQueryInterface::with()]] on how to specify this argument.
1814
     * @param bool $asArray whether to load each related model as an array or an object (if the relation itself does not specify that).
1815
     * @since 2.0.50
1816
     */
1817
    public static function loadRelationsFor(&$models, $relationNames, $asArray = false)
1818
    {
1819
        // ActiveQueryTrait::findWith() called below assumes $models array is non-empty.
1820
        if (empty($models)) {
1821
            return;
1822
        }
1823
1824
        static::find()->asArray($asArray)->findWith((array)$relationNames, $models);
0 ignored issues
show
Bug introduced by
The method findWith() does not exist on yii\db\ActiveQueryInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to yii\db\ActiveQueryInterface. ( Ignorable by Annotation )

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

1824
        static::find()->asArray($asArray)->/** @scrutinizer ignore-call */ findWith((array)$relationNames, $models);
Loading history...
1825
    }
1826
1827
    /**
1828
     * Eager loads related models for the already loaded primary model.
1829
     *
1830
     * Helps to reduce the number of queries performed against database if some related models are only used
1831
     * when a specific condition is met. For example:
1832
     *
1833
     * ```php
1834
     * $customer = Customer::find()->where(['id' => 123])->one();
1835
     * if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
1836
     *     $customer->loadRelations('orders.items');
1837
     * }
1838
     * ```
1839
     *
1840
     * @param string|array $relationNames the names of the relations of this model to be loaded from database. See [[ActiveQueryInterface::with()]] on how to specify this argument.
1841
     * @param bool $asArray whether to load each relation as an array or an object (if the relation itself does not specify that).
1842
     * @since 2.0.50
1843
     */
1844
    public function loadRelations($relationNames, $asArray = false)
1845
    {
1846
        $models = [$this];
1847
        static::loadRelationsFor($models, $relationNames, $asArray);
1848
    }
1849
}
1850