Passed
Push — master ( 505fd5...4fe40f )
by Paweł
05:53 queued 20s
created

BaseActiveRecord::loadRelations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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

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

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

class Alien {}

class Dalek extends Alien {}

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

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
449 241
        $query->link = $link;
450 241
        $query->multiple = $multiple;
451 241
        return $query;
452
    }
453
454
    /**
455
     * Populates the named relation with the related records.
456
     * Note that this method does not check if the relation exists or not.
457
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
458
     * @param ActiveRecordInterface|array|null $records the related records to be populated into the relation.
459
     * @see getRelation()
460
     */
461 153
    public function populateRelation($name, $records)
462
    {
463 153
        foreach ($this->_relationsDependencies as &$relationNames) {
464 21
            unset($relationNames[$name]);
465
        }
466
467 153
        $this->_related[$name] = $records;
468 153
    }
469
470
    /**
471
     * Check whether the named relation has been populated with records.
472
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
473
     * @return bool whether relation has been populated with records.
474
     * @see getRelation()
475
     */
476 102
    public function isRelationPopulated($name)
477
    {
478 102
        return array_key_exists($name, $this->_related);
479
    }
480
481
    /**
482
     * Returns all populated related records.
483
     * @return array an array of related records indexed by relation names.
484
     * @see getRelation()
485
     */
486 6
    public function getRelatedRecords()
487
    {
488 6
        return $this->_related;
489
    }
490
491
    /**
492
     * Returns a value indicating whether the model has an attribute with the specified name.
493
     * @param string $name the name of the attribute
494
     * @return bool whether the model has an attribute with the specified name.
495
     */
496 378
    public function hasAttribute($name)
497
    {
498 378
        return isset($this->_attributes[$name]) || in_array($name, $this->attributes(), true);
499
    }
500
501
    /**
502
     * Returns the named attribute value.
503
     * If this record is the result of a query and the attribute is not loaded,
504
     * `null` will be returned.
505
     * @param string $name the attribute name
506
     * @return mixed the attribute value. `null` if the attribute is not set or does not exist.
507
     * @see hasAttribute()
508
     */
509 4
    public function getAttribute($name)
510
    {
511 4
        return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
512
    }
513
514
    /**
515
     * Sets the named attribute value.
516
     * @param string $name the attribute name
517
     * @param mixed $value the attribute value.
518
     * @throws InvalidArgumentException if the named attribute does not exist.
519
     * @see hasAttribute()
520
     */
521 107
    public function setAttribute($name, $value)
522
    {
523 107
        if ($this->hasAttribute($name)) {
524
            if (
525 107
                !empty($this->_relationsDependencies[$name])
526 107
                && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
527
            ) {
528 6
                $this->resetDependentRelations($name);
529
            }
530 107
            $this->_attributes[$name] = $value;
531
        } else {
532
            throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
533
        }
534 107
    }
535
536
    /**
537
     * Returns the old attribute values.
538
     * @return array the old attribute values (name-value pairs)
539
     */
540
    public function getOldAttributes()
541
    {
542
        return $this->_oldAttributes === null ? [] : $this->_oldAttributes;
543
    }
544
545
    /**
546
     * Sets the old attribute values.
547
     * All existing old attribute values will be discarded.
548
     * @param array|null $values old attribute values to be set.
549
     * If set to `null` this record is considered to be [[isNewRecord|new]].
550
     */
551 115
    public function setOldAttributes($values)
552
    {
553 115
        $this->_oldAttributes = $values;
554 115
    }
555
556
    /**
557
     * Returns the old value of the named attribute.
558
     * If this record is the result of a query and the attribute is not loaded,
559
     * `null` will be returned.
560
     * @param string $name the attribute name
561
     * @return mixed the old attribute value. `null` if the attribute is not loaded before
562
     * or does not exist.
563
     * @see hasAttribute()
564
     */
565
    public function getOldAttribute($name)
566
    {
567
        return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
568
    }
569
570
    /**
571
     * Sets the old value of the named attribute.
572
     * @param string $name the attribute name
573
     * @param mixed $value the old attribute value.
574
     * @throws InvalidArgumentException if the named attribute does not exist.
575
     * @see hasAttribute()
576
     */
577 123
    public function setOldAttribute($name, $value)
578
    {
579 123
        if ($this->canSetOldAttribute($name)) {
580 123
            $this->_oldAttributes[$name] = $value;
581
        } else {
582
            throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
583
        }
584 123
    }
585
586
    /**
587
     * Returns if the old named attribute can be set.
588
     * @param string $name the attribute name
589
     * @return bool whether the old attribute can be set
590
     * @see setOldAttribute()
591
     */
592 123
    public function canSetOldAttribute($name)
593
    {
594 123
        return (isset($this->_oldAttributes[$name]) || $this->hasAttribute($name));
595
    }
596
597
    /**
598
     * Marks an attribute dirty.
599
     * This method may be called to force updating a record when calling [[update()]],
600
     * even if there is no change being made to the record.
601
     * @param string $name the attribute name
602
     */
603 7
    public function markAttributeDirty($name)
604
    {
605 7
        unset($this->_oldAttributes[$name]);
606 7
    }
607
608
    /**
609
     * Returns a value indicating whether the named attribute has been changed.
610
     * @param string $name the name of the attribute.
611
     * @param bool $identical whether the comparison of new and old value is made for
612
     * identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison.
613
     * This parameter is available since version 2.0.4.
614
     * @return bool whether the attribute has been changed
615
     */
616 2
    public function isAttributeChanged($name, $identical = true)
617
    {
618 2
        if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) {
619 1
            if ($identical) {
620 1
                return $this->_attributes[$name] !== $this->_oldAttributes[$name];
621
            }
622
623
            return $this->_attributes[$name] != $this->_oldAttributes[$name];
624
        }
625
626 1
        return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]);
627
    }
628
629
    /**
630
     * Returns the attribute values that have been modified since they are loaded or saved most recently.
631
     *
632
     * The comparison of new and old values is made for identical values using `===`.
633
     *
634
     * @param string[]|null $names the names of the attributes whose values may be returned if they are
635
     * changed recently. If null, [[attributes()]] will be used.
636
     * @return array the changed attribute values (name-value pairs)
637
     */
638 126
    public function getDirtyAttributes($names = null)
639
    {
640 126
        if ($names === null) {
641 123
            $names = $this->attributes();
642
        }
643 126
        $names = array_flip($names);
644 126
        $attributes = [];
645 126
        if ($this->_oldAttributes === null) {
646 112
            foreach ($this->_attributes as $name => $value) {
647 108
                if (isset($names[$name])) {
648 108
                    $attributes[$name] = $value;
649
                }
650
            }
651
        } else {
652 57
            foreach ($this->_attributes as $name => $value) {
653 57
                if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $this->isValueDifferent($value, $this->_oldAttributes[$name]))) {
654 53
                    $attributes[$name] = $value;
655
                }
656
            }
657
        }
658
659 126
        return $attributes;
660
    }
661
662
    /**
663
     * Saves the current record.
664
     *
665
     * This method will call [[insert()]] when [[isNewRecord]] is `true`, or [[update()]]
666
     * when [[isNewRecord]] is `false`.
667
     *
668
     * For example, to save a customer record:
669
     *
670
     * ```php
671
     * $customer = new Customer; // or $customer = Customer::findOne($id);
672
     * $customer->name = $name;
673
     * $customer->email = $email;
674
     * $customer->save();
675
     * ```
676
     *
677
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
678
     * before saving the record. Defaults to `true`. If the validation fails, the record
679
     * will not be saved to the database and this method will return `false`.
680
     * @param array|null $attributeNames list of attribute names that need to be saved. Defaults to null,
681
     * meaning all attributes that are loaded from DB will be saved.
682
     * @return bool whether the saving succeeded (i.e. no validation errors occurred).
683
     */
684 120
    public function save($runValidation = true, $attributeNames = null)
685
    {
686 120
        if ($this->getIsNewRecord()) {
687 106
            return $this->insert($runValidation, $attributeNames);
688
        }
689
690 31
        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 7
    public function updateAttributes($attributes)
770
    {
771 7
        $attrs = [];
772 7
        foreach ($attributes as $name => $value) {
773 7
            if (is_int($name)) {
774
                $attrs[] = $value;
775
            } else {
776 7
                $this->$name = $value;
777 7
                $attrs[] = $name;
778
            }
779
        }
780
781 7
        $values = $this->getDirtyAttributes($attrs);
782 7
        if (empty($values) || $this->getIsNewRecord()) {
783 4
            return 0;
784
        }
785
786 6
        $rows = static::updateAll($values, $this->getOldPrimaryKey(true));
787
788 6
        foreach ($values as $name => $value) {
789 6
            $this->_oldAttributes[$name] = $this->_attributes[$name];
790
        }
791
792 6
        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 41
    protected function updateInternal($attributes = null)
802
    {
803 41
        if (!$this->beforeSave(false)) {
804
            return false;
805
        }
806 41
        $values = $this->getDirtyAttributes($attributes);
807 41
        if (empty($values)) {
808 3
            $this->afterSave(false, $values);
809 3
            return 0;
810
        }
811 39
        $condition = $this->getOldPrimaryKey(true);
812 39
        $lock = $this->optimisticLock();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $lock is correct as $this->optimisticLock() targeting yii\db\BaseActiveRecord::optimisticLock() seems to always return null.

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

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

}

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

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

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

Loading history...
813 39
        if ($lock !== null) {
0 ignored issues
show
introduced by
The condition $lock !== null is always false.
Loading history...
814 5
            $values[$lock] = $this->$lock + 1;
815 5
            $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 39
        $rows = static::updateAll($values, $condition);
820
821 39
        if ($lock !== null && !$rows) {
822 4
            throw new StaleObjectException('The object being updated is outdated.');
823
        }
824
825 39
        if (isset($values[$lock])) {
826 5
            $this->$lock = $values[$lock];
827
        }
828
829 39
        $changedAttributes = [];
830 39
        foreach ($values as $name => $value) {
831 39
            $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
832 39
            $this->_oldAttributes[$name] = $value;
833
        }
834 39
        $this->afterSave(false, $changedAttributes);
835
836 39
        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 6
    public function updateCounters($counters)
857
    {
858 6
        if (static::updateAllCounters($counters, $this->getOldPrimaryKey(true)) > 0) {
859 6
            foreach ($counters as $name => $value) {
860 6
                if (!isset($this->_attributes[$name])) {
861 3
                    $this->_attributes[$name] = $value;
862
                } else {
863 3
                    $this->_attributes[$name] += $value;
864
                }
865 6
                $this->_oldAttributes[$name] = $this->_attributes[$name];
866
            }
867
868 6
            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 169
    public function getIsNewRecord()
920
    {
921 169
        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 586
    public function init()
940
    {
941 586
        parent::init();
942 586
        $this->trigger(self::EVENT_INIT);
943 586
    }
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 394
    public function afterFind()
952
    {
953 394
        $this->trigger(self::EVENT_AFTER_FIND);
954 394
    }
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 132
    public function beforeSave($insert)
981
    {
982 132
        $event = new ModelEvent();
983 132
        $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
984
985 132
        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 123
    public function afterSave($insert, $changedAttributes)
1007
    {
1008 123
        $this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE, new AfterSaveEvent([
1009 123
            'changedAttributes' => $changedAttributes,
1010
        ]));
1011 123
    }
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 7
    public function beforeDelete()
1034
    {
1035 7
        $event = new ModelEvent();
1036 7
        $this->trigger(self::EVENT_BEFORE_DELETE, $event);
1037
1038 7
        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 7
    public function afterDelete()
1048
    {
1049 7
        $this->trigger(self::EVENT_AFTER_DELETE);
1050 7
    }
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 $record BaseActiveRecord */
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 29
    protected function refreshInternal($record)
1076
    {
1077 29
        if ($record === null) {
1078 3
            return false;
1079
        }
1080 29
        foreach ($this->attributes() as $name) {
1081 29
            $this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null;
1082
        }
1083 29
        $this->_oldAttributes = $record->_oldAttributes;
1084 29
        $this->_related = [];
1085 29
        $this->_relationsDependencies = [];
1086 29
        $this->afterRefresh();
1087
1088 29
        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 29
    public function afterRefresh()
1099
    {
1100 29
        $this->trigger(self::EVENT_AFTER_REFRESH);
1101 29
    }
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 51
    public function getPrimaryKey($asArray = false)
1129
    {
1130 51
        $keys = static::primaryKey();
1131 51
        if (!$asArray && count($keys) === 1) {
1132 25
            return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null;
1133
        }
1134
1135 29
        $values = [];
1136 29
        foreach ($keys as $name) {
1137 29
            $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
1138
        }
1139
1140 29
        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 77
    public function getOldPrimaryKey($asArray = false)
1157
    {
1158 77
        $keys = static::primaryKey();
1159 77
        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 77
        if (!$asArray && count($keys) === 1) {
1163
            return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null;
1164
        }
1165
1166 77
        $values = [];
1167 77
        foreach ($keys as $name) {
1168 77
            $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
1169
        }
1170
1171 77
        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 394
    public static function populateRecord($record, $row)
1189
    {
1190 394
        $columns = array_flip($record->attributes());
1191 394
        foreach ($row as $name => $value) {
1192 394
            if (isset($columns[$name])) {
1193 394
                $record->_attributes[$name] = $value;
1194 6
            } elseif ($record->canSetProperty($name)) {
1195 6
                $record->$name = $value;
1196
            }
1197
        }
1198 394
        $record->_oldAttributes = $record->_attributes;
1199 394
        $record->_related = [];
1200 394
        $record->_relationsDependencies = [];
1201 394
    }
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 388
    public static function instantiate($row)
1217
    {
1218 388
        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
    #[\ReturnTypeWillChange]
1228 239
    public function offsetExists($offset)
1229
    {
1230 239
        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 210
    public function getRelation($name, $throwException = true)
1244
    {
1245 210
        $getter = 'get' . $name;
1246
        try {
1247
            // the relation could be defined in a behavior
1248 210
            $relation = $this->$getter();
1249 6
        } catch (UnknownMethodException $e) {
1250 6
            if ($throwException) {
1251 6
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e);
1252
            }
1253
1254
            return null;
1255
        }
1256 207
        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 207
        if (method_exists($this, $getter)) {
1265
            // relation name is case sensitive, trying to validate it when the relation is defined within this class
1266 207
            $method = new \ReflectionMethod($this, $getter);
1267 207
            $realName = lcfirst(substr($method->getName(), 3));
1268 207
            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 207
        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 9
    public function link($name, $model, $extraColumns = [])
1301
    {
1302
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1303 9
        $relation = $this->getRelation($name);
1304
1305 9
        if ($relation->via !== null) {
0 ignored issues
show
Bug introduced by
Accessing via on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1306 3
            if ($this->getIsNewRecord() || $model->getIsNewRecord()) {
1307
                throw new InvalidCallException('Unable to link models: the models being linked cannot be newly created.');
1308
            }
1309 3
            if (is_array($relation->via)) {
1310
                /* @var $viaRelation ActiveQuery */
1311 3
                list($viaName, $viaRelation) = $relation->via;
1312 3
                $viaClass = $viaRelation->modelClass;
1313
                // unset $viaName so that it can be reloaded to reflect the change
1314 3
                unset($this->_related[$viaName]);
1315
            } else {
1316
                $viaRelation = $relation->via;
1317
                $viaTable = reset($relation->via->from);
1318
            }
1319 3
            $columns = [];
1320 3
            foreach ($viaRelation->link as $a => $b) {
1321 3
                $columns[$a] = $this->$b;
1322
            }
1323 3
            foreach ($relation->link as $a => $b) {
0 ignored issues
show
Bug introduced by
Accessing link on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1324 3
                $columns[$b] = $model->$a;
1325
            }
1326 3
            foreach ($extraColumns as $k => $v) {
1327 3
                $columns[$k] = $v;
1328
            }
1329 3
            if (is_array($relation->via)) {
1330
                /* @var $viaClass ActiveRecordInterface */
1331
                /* @var $record ActiveRecordInterface */
1332 3
                $record = Yii::createObject($viaClass);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaClass does not seem to be defined for all execution paths leading up to this point.
Loading history...
1333 3
                foreach ($columns as $column => $value) {
1334 3
                    $record->$column = $value;
1335
                }
1336 3
                $record->insert(false);
1337
            } else {
1338
                /* @var $viaTable string */
1339 3
                static::getDb()->createCommand()->insert($viaTable, $columns)->execute();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaTable does not seem to be defined for all execution paths leading up to this point.
Loading history...
1340
            }
1341
        } else {
1342 9
            $p1 = $model->isPrimaryKey(array_keys($relation->link));
1343 9
            $p2 = static::isPrimaryKey(array_values($relation->link));
1344 9
            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 9
            } elseif ($p1) {
1354 3
                $this->bindModels(array_flip($relation->link), $this, $model);
1355 9
            } elseif ($p2) {
1356 9
                $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 9
        if (!$relation->multiple) {
0 ignored issues
show
Bug introduced by
Accessing multiple on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1364 3
            $this->_related[$name] = $model;
1365 9
        } elseif (isset($this->_related[$name])) {
1366 9
            if ($relation->indexBy !== null) {
0 ignored issues
show
Bug introduced by
Accessing indexBy on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1367 6
                if ($relation->indexBy instanceof \Closure) {
1368 3
                    $index = call_user_func($relation->indexBy, $model);
1369
                } else {
1370 3
                    $index = $model->{$relation->indexBy};
1371
                }
1372 6
                $this->_related[$name][$index] = $model;
1373
            } else {
1374 3
                $this->_related[$name][] = $model;
1375
            }
1376
        }
1377 9
    }
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 9
    public function unlink($name, $model, $delete = false)
1397
    {
1398
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1399 9
        $relation = $this->getRelation($name);
1400
1401 9
        if ($relation->via !== null) {
0 ignored issues
show
Bug introduced by
Accessing via on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1402 9
            if (is_array($relation->via)) {
1403
                /* @var $viaRelation ActiveQuery */
1404 9
                list($viaName, $viaRelation) = $relation->via;
1405 9
                $viaClass = $viaRelation->modelClass;
1406 9
                unset($this->_related[$viaName]);
1407
            } else {
1408 3
                $viaRelation = $relation->via;
1409 3
                $viaTable = reset($relation->via->from);
1410
            }
1411 9
            $columns = [];
1412 9
            foreach ($viaRelation->link as $a => $b) {
1413 9
                $columns[$a] = $this->$b;
1414
            }
1415 9
            foreach ($relation->link as $a => $b) {
0 ignored issues
show
Bug introduced by
Accessing link on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1416 9
                $columns[$b] = $model->$a;
1417
            }
1418 9
            $nulls = [];
1419 9
            foreach (array_keys($columns) as $a) {
1420 9
                $nulls[$a] = null;
1421
            }
1422 9
            if (property_exists($viaRelation, 'on') && $viaRelation->on !== null) {
1423 6
                $columns = ['and', $columns, $viaRelation->on];
1424
            }
1425 9
            if (is_array($relation->via)) {
1426
                /* @var $viaClass ActiveRecordInterface */
1427 9
                if ($delete) {
1428 6
                    $viaClass::deleteAll($columns);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaClass does not seem to be defined for all execution paths leading up to this point.
Loading history...
1429
                } else {
1430 9
                    $viaClass::updateAll($nulls, $columns);
1431
                }
1432
            } else {
1433
                /* @var $viaTable string */
1434
                /* @var $command Command */
1435 3
                $command = static::getDb()->createCommand();
1436 3
                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 9
                    $command->update($viaTable, $nulls, $columns)->execute();
1440
                }
1441
            }
1442
        } else {
1443 3
            $p1 = $model->isPrimaryKey(array_keys($relation->link));
1444 3
            $p2 = static::isPrimaryKey(array_values($relation->link));
1445 3
            if ($p2) {
1446 3
                if ($delete) {
1447 3
                    $model->delete();
1448
                } else {
1449 3
                    foreach ($relation->link as $a => $b) {
1450 3
                        $model->$a = null;
1451
                    }
1452 3
                    $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 9
        if (!$relation->multiple) {
0 ignored issues
show
Bug introduced by
Accessing multiple on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1473
            unset($this->_related[$name]);
1474 9
        } elseif (isset($this->_related[$name])) {
1475
            /* @var $b ActiveRecordInterface */
1476 9
            foreach ($this->_related[$name] as $a => $b) {
1477 9
                if ($model->getPrimaryKey() === $b->getPrimaryKey()) {
1478 9
                    unset($this->_related[$name][$a]);
1479
                }
1480
            }
1481
        }
1482 9
    }
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 18
    public function unlinkAll($name, $delete = false)
1500
    {
1501
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1502 18
        $relation = $this->getRelation($name);
1503
1504 18
        if ($relation->via !== null) {
0 ignored issues
show
Bug introduced by
Accessing via on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1505 9
            if (is_array($relation->via)) {
1506
                /* @var $viaRelation ActiveQuery */
1507 6
                list($viaName, $viaRelation) = $relation->via;
1508 6
                $viaClass = $viaRelation->modelClass;
1509 6
                unset($this->_related[$viaName]);
1510
            } else {
1511 3
                $viaRelation = $relation->via;
1512 3
                $viaTable = reset($relation->via->from);
1513
            }
1514 9
            $condition = [];
1515 9
            $nulls = [];
1516 9
            foreach ($viaRelation->link as $a => $b) {
1517 9
                $nulls[$a] = null;
1518 9
                $condition[$a] = $this->$b;
1519
            }
1520 9
            if (!empty($viaRelation->where)) {
1521
                $condition = ['and', $condition, $viaRelation->where];
1522
            }
1523 9
            if (property_exists($viaRelation, 'on') && !empty($viaRelation->on)) {
1524
                $condition = ['and', $condition, $viaRelation->on];
1525
            }
1526 9
            if (is_array($relation->via)) {
1527
                /* @var $viaClass ActiveRecordInterface */
1528 6
                if ($delete) {
1529 6
                    $viaClass::deleteAll($condition);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaClass does not seem to be defined for all execution paths leading up to this point.
Loading history...
1530
                } else {
1531 6
                    $viaClass::updateAll($nulls, $condition);
1532
                }
1533
            } else {
1534
                /* @var $viaTable string */
1535
                /* @var $command Command */
1536 3
                $command = static::getDb()->createCommand();
1537 3
                if ($delete) {
1538 3
                    $command->delete($viaTable, $condition)->execute();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $viaTable does not seem to be defined for all execution paths leading up to this point.
Loading history...
1539
                } else {
1540 9
                    $command->update($viaTable, $nulls, $condition)->execute();
1541
                }
1542
            }
1543
        } else {
1544
            /* @var $relatedModel ActiveRecordInterface */
1545 12
            $relatedModel = $relation->modelClass;
0 ignored issues
show
Bug introduced by
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1546 12
            if (!$delete && count($relation->link) === 1 && is_array($this->{$b = reset($relation->link)})) {
0 ignored issues
show
Bug introduced by
Accessing link on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1547
                // relation via array valued attribute
1548
                $this->$b = [];
1549
                $this->save(false);
1550
            } else {
1551 12
                $nulls = [];
1552 12
                $condition = [];
1553 12
                foreach ($relation->link as $a => $b) {
1554 12
                    $nulls[$a] = null;
1555 12
                    $condition[$a] = $this->$b;
1556
                }
1557 12
                if (!empty($relation->where)) {
0 ignored issues
show
Bug introduced by
Accessing where on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1558 6
                    $condition = ['and', $condition, $relation->where];
1559
                }
1560 12
                if (property_exists($relation, 'on') && !empty($relation->on)) {
1561 3
                    $condition = ['and', $condition, $relation->on];
1562
                }
1563 12
                if ($delete) {
1564 9
                    $relatedModel::deleteAll($condition);
1565
                } else {
1566 6
                    $relatedModel::updateAll($nulls, $condition);
1567
                }
1568
            }
1569
        }
1570
1571 18
        unset($this->_related[$name]);
1572 18
    }
1573
1574
    /**
1575
     * @param array $link
1576
     * @param ActiveRecordInterface $foreignModel
1577
     * @param ActiveRecordInterface $primaryModel
1578
     * @throws InvalidCallException
1579
     */
1580 9
    private function bindModels($link, $foreignModel, $primaryModel)
1581
    {
1582 9
        foreach ($link as $fk => $pk) {
1583 9
            $value = $primaryModel->$pk;
1584 9
            if ($value === null) {
1585
                throw new InvalidCallException('Unable to link models: the primary key of ' . get_class($primaryModel) . ' is null.');
1586
            }
1587 9
            if (is_array($foreignModel->$fk)) { // relation via array valued attribute
1588
                $foreignModel->{$fk}[] = $value;
1589
            } else {
1590 9
                $foreignModel->{$fk} = $value;
1591
            }
1592
        }
1593 9
        $foreignModel->save(false);
1594 9
    }
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 15
    public static function isPrimaryKey($keys)
1602
    {
1603 15
        $pks = static::primaryKey();
1604 15
        if (count($keys) === count($pks)) {
1605 15
            return count(array_intersect($keys, $pks)) === count($pks);
1606
        }
1607
1608 9
        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 58
    public function getAttributeLabel($attribute)
1626
    {
1627 58
        $model = $this;
1628 58
        $modelAttribute = $attribute;
1629 58
        for (;;) {
1630 58
            $labels = $model->attributeLabels();
1631 58
            if (isset($labels[$modelAttribute])) {
1632 11
                return $labels[$modelAttribute];
1633
            }
1634
1635 54
            $parts = explode('.', $modelAttribute, 2);
1636 54
            if (count($parts) < 2) {
1637 48
                break;
1638
            }
1639
1640 6
            list ($relationName, $modelAttribute) = $parts;
1641
1642 6
            if ($model->isRelationPopulated($relationName) && $model->$relationName instanceof self) {
1643 3
                $model = $model->$relationName;
1644
            } else {
1645
                try {
1646 6
                    $relation = $model->getRelation($relationName);
1647 6
                } catch (InvalidArgumentException $e) {
1648 6
                    break;
1649
                }
1650
                /* @var $modelClass ActiveRecordInterface */
1651 3
                $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 58
                $model = $modelClass::instance();
1653
            }
1654
        }
1655
1656 54
        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 (InvalidParamException $e) {
1684
                        return '';
1685
                    }
1686
                    /* @var $modelClass ActiveRecordInterface */
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 3
    public function fields()
1707
    {
1708 3
        $fields = array_keys($this->_attributes);
1709
1710 3
        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 3
    public function offsetUnset($offset)
1732
    {
1733 3
        if (property_exists($this, $offset)) {
1734
            $this->$offset = null;
1735
        } else {
1736 3
            unset($this->$offset);
1737
        }
1738 3
    }
1739
1740
    /**
1741
     * Resets dependent related models checking if their links contain specific attribute.
1742
     * @param string $attribute The changed attribute name.
1743
     */
1744 15
    private function resetDependentRelations($attribute)
1745
    {
1746 15
        foreach ($this->_relationsDependencies[$attribute] as $relation) {
1747 15
            unset($this->_related[$relation]);
1748
        }
1749 15
        unset($this->_relationsDependencies[$attribute]);
1750 15
    }
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 88
    private function setRelationDependencies($name, $relation, $viaRelationName = null)
1759
    {
1760 88
        if (empty($relation->via) && $relation->link) {
0 ignored issues
show
Bug introduced by
Accessing via on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Bug introduced by
Accessing link on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1761 85
            foreach ($relation->link as $attribute) {
1762 85
                $this->_relationsDependencies[$attribute][$name] = $name;
1763 85
                if ($viaRelationName !== null) {
1764 36
                    $this->_relationsDependencies[$attribute][] = $viaRelationName;
1765
                }
1766
            }
1767 51
        } elseif ($relation->via instanceof ActiveQueryInterface) {
1768 15
            $this->setRelationDependencies($name, $relation->via);
1769 39
        } elseif (is_array($relation->via)) {
1770 36
            list($viaRelationName, $viaQuery) = $relation->via;
1771 36
            $this->setRelationDependencies($name, $viaQuery, $viaRelationName);
1772
        }
1773 88
    }
1774
1775
    /**
1776
     * @param mixed $newValue
1777
     * @param mixed $oldValue
1778
     * @return bool
1779
     * @since 2.0.48
1780
     */
1781 57
    private function isValueDifferent($newValue, $oldValue)
1782
    {
1783 57
        if (is_array($newValue) && is_array($oldValue) && ArrayHelper::isAssociative($oldValue)) {
1784 7
            $newValue = ArrayHelper::recursiveSort($newValue);
1785 7
            $oldValue = ArrayHelper::recursiveSort($oldValue);
1786
        }
1787
1788 57
        return $newValue !== $oldValue;
1789
    }
1790
1791
    /**
1792
     * Eager loads related models for the already loaded primary models.
1793
     *
1794
     * Helps to reduce the number of queries performed against database if some related models are only used
1795
     * when a specific condition is met. For example:
1796
     *
1797
     * ```php
1798
     * $customers = Customer::find()->where(['country_id' => 123])->all();
1799
     * if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
1800
     *     Customer::loadRelationsFor($customers, 'orders.items');
1801
     * }
1802
     * ```
1803
     *
1804
     * @param array|ActiveRecordInterface[] $models array of primary models. Each model should have the same type and can be:
1805
     * - an active record instance;
1806
     * - active record instance represented by array (i.e. active record was loaded using [[ActiveQuery::asArray()]]).
1807
     * @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.
1808
     * @param bool $asArray whether to load each related model as an array or an object (if the relation itself does not specify that).
1809
     * @since 2.0.49
1810
     */
1811 3
    public static function loadRelationsFor(&$models, $relationNames, $asArray = false)
1812
    {
1813
        // ActiveQueryTrait::findWith() called below assumes $models array is non-empty.
1814 3
        if (empty($models)) {
1815
            return;
1816
        }
1817
1818 3
        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

1818
        static::find()->asArray($asArray)->/** @scrutinizer ignore-call */ findWith((array)$relationNames, $models);
Loading history...
1819 3
    }
1820
1821
    /**
1822
     * Eager loads related models for the already loaded primary model.
1823
     *
1824
     * Helps to reduce the number of queries performed against database if some related models are only used
1825
     * when a specific condition is met. For example:
1826
     *
1827
     * ```php
1828
     * $customer = Customer::find()->where(['id' => 123])->one();
1829
     * if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
1830
     *     $customer->loadRelations('orders.items');
1831
     * }
1832
     * ```
1833
     *
1834
     * @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.
1835
     * @param bool $asArray whether to load each relation as an array or an object (if the relation itself does not specify that).
1836
     * @since 2.0.49
1837
     */
1838 3
    public function loadRelations($relationNames, $asArray = false)
1839
    {
1840 3
        $models = [$this];
1841 3
        static::loadRelationsFor($models, $relationNames, $asArray);
1842 3
    }
1843
}
1844