Completed
Push — master ( 1500e7...dc452b )
by Dmitry
63:45 queued 60:13
created

BaseActiveRecord::resetDependentRelations()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://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 array $dirtyAttributes The changed attribute values (name-value pairs). This property is
27
 * read-only.
28
 * @property bool $isNewRecord Whether the record is new and should be inserted when calling [[save()]].
29
 * @property array $oldAttributes The old attribute values (name-value pairs). Note that the type of this
30
 * property differs in getter and setter. See [[getOldAttributes()]] and [[setOldAttributes()]] for details.
31
 * @property mixed $oldPrimaryKey The old primary key value. An array (column name => column value) is
32
 * returned if the primary key is composite. A string is returned otherwise (null will be returned if the key
33
 * value is null). This property is read-only.
34
 * @property mixed $primaryKey The primary key value. An array (column name => column value) is returned if
35
 * the primary key is composite. A string is returned otherwise (null will be returned if the key value is null).
36
 * This property is read-only.
37
 * @property array $relatedRecords An array of related records indexed by relation names. This property is
38
 * read-only.
39
 *
40
 * @author Qiang Xue <[email protected]>
41
 * @author Carsten Brandt <[email protected]>
42
 * @since 2.0
43
 */
44
abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
45
{
46
    /**
47
     * @event Event an event that is triggered when the record is initialized via [[init()]].
48
     */
49
    const EVENT_INIT = 'init';
50
    /**
51
     * @event Event an event that is triggered after the record is created and populated with query result.
52
     */
53
    const EVENT_AFTER_FIND = 'afterFind';
54
    /**
55
     * @event ModelEvent an event that is triggered before inserting a record.
56
     * You may set [[ModelEvent::isValid]] to be `false` to stop the insertion.
57
     */
58
    const EVENT_BEFORE_INSERT = 'beforeInsert';
59
    /**
60
     * @event AfterSaveEvent an event that is triggered after a record is inserted.
61
     */
62
    const EVENT_AFTER_INSERT = 'afterInsert';
63
    /**
64
     * @event ModelEvent an event that is triggered before updating a record.
65
     * You may set [[ModelEvent::isValid]] to be `false` to stop the update.
66
     */
67
    const EVENT_BEFORE_UPDATE = 'beforeUpdate';
68
    /**
69
     * @event AfterSaveEvent an event that is triggered after a record is updated.
70
     */
71
    const EVENT_AFTER_UPDATE = 'afterUpdate';
72
    /**
73
     * @event ModelEvent an event that is triggered before deleting a record.
74
     * You may set [[ModelEvent::isValid]] to be `false` to stop the deletion.
75
     */
76
    const EVENT_BEFORE_DELETE = 'beforeDelete';
77
    /**
78
     * @event Event an event that is triggered after a record is deleted.
79
     */
80
    const EVENT_AFTER_DELETE = 'afterDelete';
81
    /**
82
     * @event Event an event that is triggered after a record is refreshed.
83
     * @since 2.0.8
84
     */
85
    const EVENT_AFTER_REFRESH = 'afterRefresh';
86
87
    /**
88
     * @var array attribute values indexed by attribute names
89
     */
90
    private $_attributes = [];
91
    /**
92
     * @var array|null old attribute values indexed by attribute names.
93
     * This is `null` if the record [[isNewRecord|is new]].
94
     */
95
    private $_oldAttributes;
96
    /**
97
     * @var array related models indexed by the relation names
98
     */
99
    private $_related = [];
100
    /**
101
     * @var array relation names indexed by their link attributes
102
     */
103
    private $_relationsDependencies = [];
104
105
106
    /**
107
     * {@inheritdoc}
108
     * @return static|null ActiveRecord instance matching the condition, or `null` if nothing matches.
109
     */
110 187
    public static function findOne($condition)
111
    {
112 187
        return static::findByCondition($condition)->one();
0 ignored issues
show
Bug Compatibility introduced by
The expression static::findByCondition($condition)->one(); of type yii\db\ActiveRecordInterface|array|null adds the type array to the return on line 112 which is incompatible with the return type declared by the interface yii\db\ActiveRecordInterface::findOne of type yii\db\ActiveRecordInterface.
Loading history...
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     * @return static[] an array of ActiveRecord instances, or an empty array if nothing matches.
118
     */
119
    public static function findAll($condition)
120
    {
121
        return static::findByCondition($condition)->all();
122
    }
123
124
    /**
125
     * Finds ActiveRecord instance(s) by the given condition.
126
     * This method is internally called by [[findOne()]] and [[findAll()]].
127
     * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter
128
     * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance.
129
     * @throws InvalidConfigException if there is no primary key defined
130
     * @internal
131
     */
132
    protected static function findByCondition($condition)
133
    {
134
        $query = static::find();
135
136
        if (!ArrayHelper::isAssociative($condition)) {
137
            // query by primary key
138
            $primaryKey = static::primaryKey();
139
            if (isset($primaryKey[0])) {
140
                $condition = [$primaryKey[0] => $condition];
141
            } else {
142
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
143
            }
144
        }
145
146
        return $query->andWhere($condition);
147
    }
148
149
    /**
150
     * Updates the whole table using the provided attribute values and conditions.
151
     *
152
     * For example, to change the status to be 1 for all customers whose status is 2:
153
     *
154
     * ```php
155
     * Customer::updateAll(['status' => 1], 'status = 2');
156
     * ```
157
     *
158
     * @param array $attributes attribute values (name-value pairs) to be saved into the table
159
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
160
     * Please refer to [[Query::where()]] on how to specify this parameter.
161
     * @return int the number of rows updated
162
     * @throws NotSupportedException if not overridden
163
     */
164
    public static function updateAll($attributes, $condition = '')
165
    {
166
        throw new NotSupportedException(__METHOD__ . ' is not supported.');
167
    }
168
169
    /**
170
     * Updates the whole table using the provided counter changes and conditions.
171
     *
172
     * For example, to increment all customers' age by 1,
173
     *
174
     * ```php
175
     * Customer::updateAllCounters(['age' => 1]);
176
     * ```
177
     *
178
     * @param array $counters the counters to be updated (attribute name => increment value).
179
     * Use negative values if you want to decrement the counters.
180
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
181
     * Please refer to [[Query::where()]] on how to specify this parameter.
182
     * @return int the number of rows updated
183
     * @throws NotSupportedException if not overrided
184
     */
185
    public static function updateAllCounters($counters, $condition = '')
186
    {
187
        throw new NotSupportedException(__METHOD__ . ' is not supported.');
188
    }
189
190
    /**
191
     * Deletes rows in the table using the provided conditions.
192
     * WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
193
     *
194
     * For example, to delete all customers whose status is 3:
195
     *
196
     * ```php
197
     * Customer::deleteAll('status = 3');
198
     * ```
199
     *
200
     * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
201
     * Please refer to [[Query::where()]] on how to specify this parameter.
202
     * @return int the number of rows deleted
203
     * @throws NotSupportedException if not overridden.
204
     */
205
    public static function deleteAll($condition = null)
206
    {
207
        throw new NotSupportedException(__METHOD__ . ' is not supported.');
208
    }
209
210
    /**
211
     * Returns the name of the column that stores the lock version for implementing optimistic locking.
212
     *
213
     * Optimistic locking allows multiple users to access the same record for edits and avoids
214
     * potential conflicts. In case when a user attempts to save the record upon some staled data
215
     * (because another user has modified the data), a [[StaleObjectException]] exception will be thrown,
216
     * and the update or deletion is skipped.
217
     *
218
     * Optimistic locking is only supported by [[update()]] and [[delete()]].
219
     *
220
     * To use Optimistic locking:
221
     *
222
     * 1. Create a column to store the version number of each row. The column type should be `BIGINT DEFAULT 0`.
223
     *    Override this method to return the name of this column.
224
     * 2. Add a `required` validation rule for the version column to ensure the version value is submitted.
225
     * 3. In the Web form that collects the user input, add a hidden field that stores
226
     *    the lock version of the recording 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 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 33
    public function optimisticLock()
235
    {
236 33
        return null;
237
    }
238
239
    /**
240
     * {@inheritdoc}
241
     */
242 3
    public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
243
    {
244 3
        if (parent::canGetProperty($name, $checkVars, $checkBehaviors)) {
245 3
            return true;
246
        }
247
248
        try {
249 3
            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 9
    public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
260
    {
261 9
        if (parent::canSetProperty($name, $checkVars, $checkBehaviors)) {
262 6
            return true;
263
        }
264
265
        try {
266 3
            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 373
    public function __get($name)
283
    {
284 373
        if (isset($this->_attributes[$name]) || array_key_exists($name, $this->_attributes)) {
285 358
            return $this->_attributes[$name];
286
        }
287
288 189
        if ($this->hasAttribute($name)) {
289 44
            return null;
290
        }
291
292 163
        if (isset($this->_related[$name]) || array_key_exists($name, $this->_related)) {
293 90
            return $this->_related[$name];
294
        }
295 115
        $value = parent::__get($name);
296 115
        if ($value instanceof ActiveQueryInterface) {
297 70
            $this->setRelationDependencies($name, $value);
298 70
            return $this->_related[$name] = $value->findFor($name, $this);
299
        }
300
301 54
        return $value;
302
    }
303
304
    /**
305
     * PHP setter magic method.
306
     * This method is overridden so that AR attributes can be accessed like properties.
307
     * @param string $name property name
308
     * @param mixed $value property value
309
     */
310 182
    public function __set($name, $value)
311
    {
312 182
        if ($this->hasAttribute($name)) {
313
            if (
314 182
                !empty($this->_relationsDependencies[$name])
315 182
                && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
316
            ) {
317 15
                $this->resetDependentRelations($name);
318
            }
319 182
            $this->_attributes[$name] = $value;
320
        } else {
321 5
            parent::__set($name, $value);
322
        }
323 182
    }
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 56
    public function __isset($name)
332
    {
333
        try {
334 56
            return $this->__get($name) !== null;
335
        } catch (\Exception $e) {
336
            return false;
337
        }
338
    }
339
340
    /**
341
     * Sets a component property to be null.
342
     * This method overrides the parent implementation by clearing
343
     * the specified attribute value.
344
     * @param string $name the property name or the event name
345
     */
346 15
    public function __unset($name)
347
    {
348 15
        if ($this->hasAttribute($name)) {
349 9
            unset($this->_attributes[$name]);
350 9
            if (!empty($this->_relationsDependencies[$name])) {
351 9
                $this->resetDependentRelations($name);
352
            }
353 6
        } elseif (array_key_exists($name, $this->_related)) {
354 6
            unset($this->_related[$name]);
355
        } elseif ($this->getRelation($name, false) === null) {
356
            parent::__unset($name);
357
        }
358 15
    }
359
360
    /**
361
     * Declares a `has-one` relation.
362
     * The declaration is returned in terms of a relational [[ActiveQuery]] instance
363
     * through which the related record can be queried and retrieved back.
364
     *
365
     * A `has-one` relation means that there is at most one related record matching
366
     * the criteria set by this relation, e.g., a customer has one country.
367
     *
368
     * For example, to declare the `country` relation for `Customer` class, we can write
369
     * the following code in the `Customer` class:
370
     *
371
     * ```php
372
     * public function getCountry()
373
     * {
374
     *     return $this->hasOne(Country::className(), ['id' => 'country_id']);
375
     * }
376
     * ```
377
     *
378
     * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name
379
     * in the related class `Country`, while the 'country_id' value refers to an attribute name
380
     * in the current AR class.
381
     *
382
     * Call methods declared in [[ActiveQuery]] to further customize the relation.
383
     *
384
     * @param string $class the class name of the related record
385
     * @param array $link the primary-foreign key constraint. The keys of the array refer to
386
     * the attributes of the record associated with the `$class` model, while the values of the
387
     * array refer to the corresponding attributes in **this** AR class.
388
     * @return ActiveQueryInterface the relational query object.
389
     */
390 70
    public function hasOne($class, $link)
391
    {
392 70
        return $this->createRelationQuery($class, $link, false);
393
    }
394
395
    /**
396
     * Declares a `has-many` relation.
397
     * The declaration is returned in terms of a relational [[ActiveQuery]] instance
398
     * through which the related record can be queried and retrieved back.
399
     *
400
     * A `has-many` relation means that there are multiple related records matching
401
     * the criteria set by this relation, e.g., a customer has many orders.
402
     *
403
     * For example, to declare the `orders` relation for `Customer` class, we can write
404
     * the following code in the `Customer` class:
405
     *
406
     * ```php
407
     * public function getOrders()
408
     * {
409
     *     return $this->hasMany(Order::className(), ['customer_id' => 'id']);
410
     * }
411
     * ```
412
     *
413
     * Note that in the above, the 'customer_id' key in the `$link` parameter refers to
414
     * an attribute name in the related class `Order`, while the 'id' value refers to
415
     * an attribute name in the current AR class.
416
     *
417
     * Call methods declared in [[ActiveQuery]] to further customize the relation.
418
     *
419
     * @param string $class the class name of the related record
420
     * @param array $link the primary-foreign key constraint. The keys of the array refer to
421
     * the attributes of the record associated with the `$class` model, while the values of the
422
     * array refer to the corresponding attributes in **this** AR class.
423
     * @return ActiveQueryInterface the relational query object.
424
     */
425 147
    public function hasMany($class, $link)
426
    {
427 147
        return $this->createRelationQuery($class, $link, true);
428
    }
429
430
    /**
431
     * Creates a query instance for `has-one` or `has-many` relation.
432
     * @param string $class the class name of the related record.
433
     * @param array $link the primary-foreign key constraint.
434
     * @param bool $multiple whether this query represents a relation to more than one record.
435
     * @return ActiveQueryInterface the relational query object.
436
     * @since 2.0.12
437
     * @see hasOne()
438
     * @see hasMany()
439
     */
440 175
    protected function createRelationQuery($class, $link, $multiple)
441
    {
442
        /* @var $class ActiveRecordInterface */
443
        /* @var $query ActiveQuery */
444 175
        $query = $class::find();
445 175
        $query->primaryModel = $this;
0 ignored issues
show
Documentation Bug introduced by
$this is of type object<yii\db\BaseActiveRecord>, but the property $primaryModel was declared to be of type object<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...
446 175
        $query->link = $link;
447 175
        $query->multiple = $multiple;
448 175
        return $query;
449
    }
450
451
    /**
452
     * Populates the named relation with the related records.
453
     * Note that this method does not check if the relation exists or not.
454
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
455
     * @param ActiveRecordInterface|array|null $records the related records to be populated into the relation.
456
     * @see getRelation()
457
     */
458 117
    public function populateRelation($name, $records)
459
    {
460 117
        $this->_related[$name] = $records;
461 117
    }
462
463
    /**
464
     * Check whether the named relation has been populated with records.
465
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
466
     * @return bool whether relation has been populated with records.
467
     * @see getRelation()
468
     */
469 48
    public function isRelationPopulated($name)
470
    {
471 48
        return array_key_exists($name, $this->_related);
472
    }
473
474
    /**
475
     * Returns all populated related records.
476
     * @return array an array of related records indexed by relation names.
477
     * @see getRelation()
478
     */
479 6
    public function getRelatedRecords()
480
    {
481 6
        return $this->_related;
482
    }
483
484
    /**
485
     * Returns a value indicating whether the model has an attribute with the specified name.
486
     * @param string $name the name of the attribute
487
     * @return bool whether the model has an attribute with the specified name.
488
     */
489 288
    public function hasAttribute($name)
490
    {
491 288
        return isset($this->_attributes[$name]) || in_array($name, $this->attributes(), true);
492
    }
493
494
    /**
495
     * Returns the named attribute value.
496
     * If this record is the result of a query and the attribute is not loaded,
497
     * `null` will be returned.
498
     * @param string $name the attribute name
499
     * @return mixed the attribute value. `null` if the attribute is not set or does not exist.
500
     * @see hasAttribute()
501
     */
502
    public function getAttribute($name)
503
    {
504
        return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
505
    }
506
507
    /**
508
     * Sets the named attribute value.
509
     * @param string $name the attribute name
510
     * @param mixed $value the attribute value.
511
     * @throws InvalidArgumentException if the named attribute does not exist.
512
     * @see hasAttribute()
513
     */
514 83
    public function setAttribute($name, $value)
515
    {
516 83
        if ($this->hasAttribute($name)) {
517
            if (
518 83
                !empty($this->_relationsDependencies[$name])
519 83
                && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
520
            ) {
521 6
                $this->resetDependentRelations($name);
522
            }
523 83
            $this->_attributes[$name] = $value;
524
        } else {
525
            throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
526
        }
527 83
    }
528
529
    /**
530
     * Returns the old attribute values.
531
     * @return array the old attribute values (name-value pairs)
532
     */
533
    public function getOldAttributes()
534
    {
535
        return $this->_oldAttributes === null ? [] : $this->_oldAttributes;
536
    }
537
538
    /**
539
     * Sets the old attribute values.
540
     * All existing old attribute values will be discarded.
541
     * @param array|null $values old attribute values to be set.
542
     * If set to `null` this record is considered to be [[isNewRecord|new]].
543
     */
544 94
    public function setOldAttributes($values)
545
    {
546 94
        $this->_oldAttributes = $values;
547 94
    }
548
549
    /**
550
     * Returns the old value of the named attribute.
551
     * If this record is the result of a query and the attribute is not loaded,
552
     * `null` will be returned.
553
     * @param string $name the attribute name
554
     * @return mixed the old attribute value. `null` if the attribute is not loaded before
555
     * or does not exist.
556
     * @see hasAttribute()
557
     */
558
    public function getOldAttribute($name)
559
    {
560
        return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
561
    }
562
563
    /**
564
     * Sets the old value of the named attribute.
565
     * @param string $name the attribute name
566
     * @param mixed $value the old attribute value.
567
     * @throws InvalidArgumentException if the named attribute does not exist.
568
     * @see hasAttribute()
569
     */
570
    public function setOldAttribute($name, $value)
571
    {
572
        if (isset($this->_oldAttributes[$name]) || $this->hasAttribute($name)) {
573
            $this->_oldAttributes[$name] = $value;
574
        } else {
575
            throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
576
        }
577
    }
578
579
    /**
580
     * Marks an attribute dirty.
581
     * This method may be called to force updating a record when calling [[update()]],
582
     * even if there is no change being made to the record.
583
     * @param string $name the attribute name
584
     */
585 3
    public function markAttributeDirty($name)
586
    {
587 3
        unset($this->_oldAttributes[$name]);
588 3
    }
589
590
    /**
591
     * Returns a value indicating whether the named attribute has been changed.
592
     * @param string $name the name of the attribute.
593
     * @param bool $identical whether the comparison of new and old value is made for
594
     * identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison.
595
     * This parameter is available since version 2.0.4.
596
     * @return bool whether the attribute has been changed
597
     */
598 2
    public function isAttributeChanged($name, $identical = true)
599
    {
600 2
        if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) {
601 1
            if ($identical) {
602 1
                return $this->_attributes[$name] !== $this->_oldAttributes[$name];
603
            }
604
605
            return $this->_attributes[$name] != $this->_oldAttributes[$name];
606
        }
607
608 1
        return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]);
609
    }
610
611
    /**
612
     * Returns the attribute values that have been modified since they are loaded or saved most recently.
613
     *
614
     * The comparison of new and old values is made for identical values using `===`.
615
     *
616
     * @param string[]|null $names the names of the attributes whose values may be returned if they are
617
     * changed recently. If null, [[attributes()]] will be used.
618
     * @return array the changed attribute values (name-value pairs)
619
     */
620 104
    public function getDirtyAttributes($names = null)
621
    {
622 104
        if ($names === null) {
623 101
            $names = $this->attributes();
624
        }
625 104
        $names = array_flip($names);
626 104
        $attributes = [];
627 104
        if ($this->_oldAttributes === null) {
628 91
            foreach ($this->_attributes as $name => $value) {
629 87
                if (isset($names[$name])) {
630 91
                    $attributes[$name] = $value;
631
                }
632
            }
633
        } else {
634 39
            foreach ($this->_attributes as $name => $value) {
635 39
                if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $value !== $this->_oldAttributes[$name])) {
636 39
                    $attributes[$name] = $value;
637
                }
638
            }
639
        }
640
641 104
        return $attributes;
642
    }
643
644
    /**
645
     * Saves the current record.
646
     *
647
     * This method will call [[insert()]] when [[isNewRecord]] is `true`, or [[update()]]
648
     * when [[isNewRecord]] is `false`.
649
     *
650
     * For example, to save a customer record:
651
     *
652
     * ```php
653
     * $customer = new Customer; // or $customer = Customer::findOne($id);
654
     * $customer->name = $name;
655
     * $customer->email = $email;
656
     * $customer->save();
657
     * ```
658
     *
659
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
660
     * before saving the record. Defaults to `true`. If the validation fails, the record
661
     * will not be saved to the database and this method will return `false`.
662
     * @param array $attributeNames list of attribute names that need to be saved. Defaults to null,
663
     * meaning all attributes that are loaded from DB will be saved.
664
     * @return bool whether the saving succeeded (i.e. no validation errors occurred).
665
     */
666 98
    public function save($runValidation = true, $attributeNames = null)
667
    {
668 98
        if ($this->getIsNewRecord()) {
669 85
            return $this->insert($runValidation, $attributeNames);
670
        }
671
672 28
        return $this->update($runValidation, $attributeNames) !== false;
673
    }
674
675
    /**
676
     * Saves the changes to this active record into the associated database table.
677
     *
678
     * This method performs the following steps in order:
679
     *
680
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
681
     *    returns `false`, the rest of the steps will be skipped;
682
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
683
     *    failed, the rest of the steps will be skipped;
684
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
685
     *    the rest of the steps will be skipped;
686
     * 4. save the record into database. If this fails, it will skip the rest of the steps;
687
     * 5. call [[afterSave()]];
688
     *
689
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
690
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
691
     * will be raised by the corresponding methods.
692
     *
693
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
694
     *
695
     * For example, to update a customer record:
696
     *
697
     * ```php
698
     * $customer = Customer::findOne($id);
699
     * $customer->name = $name;
700
     * $customer->email = $email;
701
     * $customer->update();
702
     * ```
703
     *
704
     * Note that it is possible the update does not affect any row in the table.
705
     * In this case, this method will return 0. For this reason, you should use the following
706
     * code to check if update() is successful or not:
707
     *
708
     * ```php
709
     * if ($customer->update() !== false) {
710
     *     // update successful
711
     * } else {
712
     *     // update failed
713
     * }
714
     * ```
715
     *
716
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
717
     * before saving the record. Defaults to `true`. If the validation fails, the record
718
     * will not be saved to the database and this method will return `false`.
719
     * @param array $attributeNames list of attribute names that need to be saved. Defaults to null,
720
     * meaning all attributes that are loaded from DB will be saved.
721
     * @return int|false the number of rows affected, or `false` if validation fails
722
     * or [[beforeSave()]] stops the updating process.
723
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
724
     * being updated is outdated.
725
     * @throws Exception in case update failed.
726
     */
727
    public function update($runValidation = true, $attributeNames = null)
728
    {
729
        if ($runValidation && !$this->validate($attributeNames)) {
0 ignored issues
show
Bug introduced by
It seems like $attributeNames defined by parameter $attributeNames on line 727 can also be of type array; however, yii\base\Model::validate() does only seem to accept array<integer,string>|string|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
730
            return false;
731
        }
732
733
        return $this->updateInternal($attributeNames);
734
    }
735
736
    /**
737
     * Updates the specified attributes.
738
     *
739
     * This method is a shortcut to [[update()]] when data validation is not needed
740
     * and only a small set attributes need to be updated.
741
     *
742
     * You may specify the attributes to be updated as name list or name-value pairs.
743
     * If the latter, the corresponding attribute values will be modified accordingly.
744
     * The method will then save the specified attributes into database.
745
     *
746
     * Note that this method will **not** perform data validation and will **not** trigger events.
747
     *
748
     * @param array $attributes the attributes (names or name-value pairs) to be updated
749
     * @return int the number of rows affected.
750
     */
751 4
    public function updateAttributes($attributes)
752
    {
753 4
        $attrs = [];
754 4
        foreach ($attributes as $name => $value) {
755 4
            if (is_int($name)) {
756
                $attrs[] = $value;
757
            } else {
758 4
                $this->$name = $value;
759 4
                $attrs[] = $name;
760
            }
761
        }
762
763 4
        $values = $this->getDirtyAttributes($attrs);
764 4
        if (empty($values) || $this->getIsNewRecord()) {
765 4
            return 0;
766
        }
767
768 3
        $rows = static::updateAll($values, $this->getOldPrimaryKey(true));
769
770 3
        foreach ($values as $name => $value) {
771 3
            $this->_oldAttributes[$name] = $this->_attributes[$name];
772
        }
773
774 3
        return $rows;
775
    }
776
777
    /**
778
     * @see update()
779
     * @param array $attributes attributes to update
780
     * @return int|false the number of rows affected, or false if [[beforeSave()]] stops the updating process.
781
     * @throws StaleObjectException
782
     */
783 35
    protected function updateInternal($attributes = null)
784
    {
785 35
        if (!$this->beforeSave(false)) {
786
            return false;
787
        }
788 35
        $values = $this->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 783 can also be of type array; however, yii\db\BaseActiveRecord::getDirtyAttributes() does only seem to accept array<integer,string>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
789 35
        if (empty($values)) {
790 3
            $this->afterSave(false, $values);
791 3
            return 0;
792
        }
793 33
        $condition = $this->getOldPrimaryKey(true);
794 33
        $lock = $this->optimisticLock();
795 33
        if ($lock !== null) {
796 3
            $values[$lock] = $this->$lock + 1;
797 3
            $condition[$lock] = $this->$lock;
798
        }
799
        // We do not check the return value of updateAll() because it's possible
800
        // that the UPDATE statement doesn't change anything and thus returns 0.
801 33
        $rows = static::updateAll($values, $condition);
802
803 33
        if ($lock !== null && !$rows) {
804 3
            throw new StaleObjectException('The object being updated is outdated.');
805
        }
806
807 33
        if (isset($values[$lock])) {
808 3
            $this->$lock = $values[$lock];
809
        }
810
811 33
        $changedAttributes = [];
812 33
        foreach ($values as $name => $value) {
813 33
            $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
814 33
            $this->_oldAttributes[$name] = $value;
815
        }
816 33
        $this->afterSave(false, $changedAttributes);
817
818 33
        return $rows;
819
    }
820
821
    /**
822
     * Updates one or several counter columns for the current AR object.
823
     * Note that this method differs from [[updateAllCounters()]] in that it only
824
     * saves counters for the current AR object.
825
     *
826
     * An example usage is as follows:
827
     *
828
     * ```php
829
     * $post = Post::findOne($id);
830
     * $post->updateCounters(['view_count' => 1]);
831
     * ```
832
     *
833
     * @param array $counters the counters to be updated (attribute name => increment value)
834
     * Use negative values if you want to decrement the counters.
835
     * @return bool whether the saving is successful
836
     * @see updateAllCounters()
837
     */
838 6
    public function updateCounters($counters)
839
    {
840 6
        if (static::updateAllCounters($counters, $this->getOldPrimaryKey(true)) > 0) {
841 6
            foreach ($counters as $name => $value) {
842 6
                if (!isset($this->_attributes[$name])) {
843 3
                    $this->_attributes[$name] = $value;
844
                } else {
845 3
                    $this->_attributes[$name] += $value;
846
                }
847 6
                $this->_oldAttributes[$name] = $this->_attributes[$name];
848
            }
849
850 6
            return true;
851
        }
852
853
        return false;
854
    }
855
856
    /**
857
     * Deletes the table row corresponding to this active record.
858
     *
859
     * This method performs the following steps in order:
860
     *
861
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
862
     *    rest of the steps;
863
     * 2. delete the record from the database;
864
     * 3. call [[afterDelete()]].
865
     *
866
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
867
     * will be raised by the corresponding methods.
868
     *
869
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
870
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
871
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
872
     * being deleted is outdated.
873
     * @throws Exception in case delete failed.
874
     */
875
    public function delete()
876
    {
877
        $result = false;
878
        if ($this->beforeDelete()) {
879
            // we do not check the return value of deleteAll() because it's possible
880
            // the record is already deleted in the database and thus the method will return 0
881
            $condition = $this->getOldPrimaryKey(true);
882
            $lock = $this->optimisticLock();
883
            if ($lock !== null) {
884
                $condition[$lock] = $this->$lock;
885
            }
886
            $result = static::deleteAll($condition);
887
            if ($lock !== null && !$result) {
888
                throw new StaleObjectException('The object being deleted is outdated.');
889
            }
890
            $this->_oldAttributes = null;
891
            $this->afterDelete();
892
        }
893
894
        return $result;
895
    }
896
897
    /**
898
     * Returns a value indicating whether the current record is new.
899
     * @return bool whether the record is new and should be inserted when calling [[save()]].
900
     */
901 141
    public function getIsNewRecord()
902
    {
903 141
        return $this->_oldAttributes === null;
904
    }
905
906
    /**
907
     * Sets the value indicating whether the record is new.
908
     * @param bool $value whether the record is new and should be inserted when calling [[save()]].
909
     * @see getIsNewRecord()
910
     */
911
    public function setIsNewRecord($value)
912
    {
913
        $this->_oldAttributes = $value ? null : $this->_attributes;
914
    }
915
916
    /**
917
     * Initializes the object.
918
     * This method is called at the end of the constructor.
919
     * The default implementation will trigger an [[EVENT_INIT]] event.
920
     */
921 402
    public function init()
922
    {
923 402
        parent::init();
924 402
        $this->trigger(self::EVENT_INIT);
925 402
    }
926
927
    /**
928
     * This method is called when the AR object is created and populated with the query result.
929
     * The default implementation will trigger an [[EVENT_AFTER_FIND]] event.
930
     * When overriding this method, make sure you call the parent implementation to ensure the
931
     * event is triggered.
932
     */
933 316
    public function afterFind()
934
    {
935 316
        $this->trigger(self::EVENT_AFTER_FIND);
936 316
    }
937
938
    /**
939
     * This method is called at the beginning of inserting or updating a record.
940
     *
941
     * The default implementation will trigger an [[EVENT_BEFORE_INSERT]] event when `$insert` is `true`,
942
     * or an [[EVENT_BEFORE_UPDATE]] event if `$insert` is `false`.
943
     * When overriding this method, make sure you call the parent implementation like the following:
944
     *
945
     * ```php
946
     * public function beforeSave($insert)
947
     * {
948
     *     if (!parent::beforeSave($insert)) {
949
     *         return false;
950
     *     }
951
     *
952
     *     // ...custom code here...
953
     *     return true;
954
     * }
955
     * ```
956
     *
957
     * @param bool $insert whether this method called while inserting a record.
958
     * If `false`, it means the method is called while updating a record.
959
     * @return bool whether the insertion or updating should continue.
960
     * If `false`, the insertion or updating will be cancelled.
961
     */
962 108
    public function beforeSave($insert)
963
    {
964 108
        $event = new ModelEvent();
965 108
        $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
966
967 108
        return $event->isValid;
968
    }
969
970
    /**
971
     * This method is called at the end of inserting or updating a record.
972
     * The default implementation will trigger an [[EVENT_AFTER_INSERT]] event when `$insert` is `true`,
973
     * or an [[EVENT_AFTER_UPDATE]] event if `$insert` is `false`. The event class used is [[AfterSaveEvent]].
974
     * When overriding this method, make sure you call the parent implementation so that
975
     * the event is triggered.
976
     * @param bool $insert whether this method called while inserting a record.
977
     * If `false`, it means the method is called while updating a record.
978
     * @param array $changedAttributes The old values of attributes that had changed and were saved.
979
     * You can use this parameter to take action based on the changes made for example send an email
980
     * when the password had changed or implement audit trail that tracks all the changes.
981
     * `$changedAttributes` gives you the old attribute values while the active record (`$this`) has
982
     * already the new, updated values.
983
     *
984
     * Note that no automatic type conversion performed by default. You may use
985
     * [[\yii\behaviors\AttributeTypecastBehavior]] to facilitate attribute typecasting.
986
     * See http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting.
987
     */
988 101
    public function afterSave($insert, $changedAttributes)
989
    {
990 101
        $this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE, new AfterSaveEvent([
991 101
            'changedAttributes' => $changedAttributes,
992
        ]));
993 101
    }
994
995
    /**
996
     * This method is invoked before deleting a record.
997
     *
998
     * The default implementation raises the [[EVENT_BEFORE_DELETE]] event.
999
     * When overriding this method, make sure you call the parent implementation like the following:
1000
     *
1001
     * ```php
1002
     * public function beforeDelete()
1003
     * {
1004
     *     if (!parent::beforeDelete()) {
1005
     *         return false;
1006
     *     }
1007
     *
1008
     *     // ...custom code here...
1009
     *     return true;
1010
     * }
1011
     * ```
1012
     *
1013
     * @return bool whether the record should be deleted. Defaults to `true`.
1014
     */
1015 6
    public function beforeDelete()
1016
    {
1017 6
        $event = new ModelEvent();
1018 6
        $this->trigger(self::EVENT_BEFORE_DELETE, $event);
1019
1020 6
        return $event->isValid;
1021
    }
1022
1023
    /**
1024
     * This method is invoked after deleting a record.
1025
     * The default implementation raises the [[EVENT_AFTER_DELETE]] event.
1026
     * You may override this method to do postprocessing after the record is deleted.
1027
     * Make sure you call the parent implementation so that the event is raised properly.
1028
     */
1029 6
    public function afterDelete()
1030
    {
1031 6
        $this->trigger(self::EVENT_AFTER_DELETE);
1032 6
    }
1033
1034
    /**
1035
     * Repopulates this active record with the latest data.
1036
     *
1037
     * If the refresh is successful, an [[EVENT_AFTER_REFRESH]] event will be triggered.
1038
     * This event is available since version 2.0.8.
1039
     *
1040
     * @return bool whether the row still exists in the database. If `true`, the latest data
1041
     * will be populated to this active record. Otherwise, this record will remain unchanged.
1042
     */
1043
    public function refresh()
1044
    {
1045
        /* @var $record BaseActiveRecord */
1046
        $record = static::findOne($this->getPrimaryKey(true));
1047
        return $this->refreshInternal($record);
1048
    }
1049
1050
    /**
1051
     * Repopulates this active record with the latest data from a newly fetched instance.
1052
     * @param BaseActiveRecord $record the record to take attributes from.
1053
     * @return bool whether refresh was successful.
1054
     * @see refresh()
1055
     * @since 2.0.13
1056
     */
1057 29
    protected function refreshInternal($record)
1058
    {
1059 29
        if ($record === null) {
1060 3
            return false;
1061
        }
1062 29
        foreach ($this->attributes() as $name) {
1063 29
            $this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null;
1064
        }
1065 29
        $this->_oldAttributes = $record->_oldAttributes;
1066 29
        $this->_related = [];
1067 29
        $this->_relationsDependencies = [];
1068 29
        $this->afterRefresh();
1069
1070 29
        return true;
1071
    }
1072
1073
    /**
1074
     * This method is called when the AR object is refreshed.
1075
     * The default implementation will trigger an [[EVENT_AFTER_REFRESH]] event.
1076
     * When overriding this method, make sure you call the parent implementation to ensure the
1077
     * event is triggered.
1078
     * @since 2.0.8
1079
     */
1080 29
    public function afterRefresh()
1081
    {
1082 29
        $this->trigger(self::EVENT_AFTER_REFRESH);
1083 29
    }
1084
1085
    /**
1086
     * Returns a value indicating whether the given active record is the same as the current one.
1087
     * The comparison is made by comparing the table names and the primary key values of the two active records.
1088
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
1089
     * @param ActiveRecordInterface $record record to compare to
1090
     * @return bool whether the two active records refer to the same row in the same database table.
1091
     */
1092
    public function equals($record)
1093
    {
1094
        if ($this->getIsNewRecord() || $record->getIsNewRecord()) {
1095
            return false;
1096
        }
1097
1098
        return get_class($this) === get_class($record) && $this->getPrimaryKey() === $record->getPrimaryKey();
1099
    }
1100
1101
    /**
1102
     * Returns the primary key value(s).
1103
     * @param bool $asArray whether to return the primary key value as an array. If `true`,
1104
     * the return value will be an array with column names as keys and column values as values.
1105
     * Note that for composite primary keys, an array will always be returned regardless of this parameter value.
1106
     * @property mixed The primary key value. An array (column name => column value) is returned if
1107
     * the primary key is composite. A string is returned otherwise (null will be returned if
1108
     * the key value is null).
1109
     * @return mixed the primary key value. An array (column name => column value) is returned if the primary key
1110
     * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
1111
     * the key value is null).
1112
     */
1113 45
    public function getPrimaryKey($asArray = false)
1114
    {
1115 45
        $keys = $this->primaryKey();
1116 45
        if (!$asArray && count($keys) === 1) {
1117 19
            return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null;
1118
        }
1119
1120 29
        $values = [];
1121 29
        foreach ($keys as $name) {
1122 29
            $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
1123
        }
1124
1125 29
        return $values;
1126
    }
1127
1128
    /**
1129
     * Returns the old primary key value(s).
1130
     * This refers to the primary key value that is populated into the record
1131
     * after executing a find method (e.g. find(), findOne()).
1132
     * The value remains unchanged even if the primary key attribute is manually assigned with a different value.
1133
     * @param bool $asArray whether to return the primary key value as an array. If `true`,
1134
     * the return value will be an array with column name as key and column value as value.
1135
     * If this is `false` (default), a scalar value will be returned for non-composite primary key.
1136
     * @property mixed The old primary key value. An array (column name => column value) is
1137
     * returned if the primary key is composite. A string is returned otherwise (null will be
1138
     * returned if the key value is null).
1139
     * @return mixed the old primary key value. An array (column name => column value) is returned if the primary key
1140
     * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
1141
     * the key value is null).
1142
     * @throws Exception if the AR model does not have a primary key
1143
     */
1144 67
    public function getOldPrimaryKey($asArray = false)
1145
    {
1146 67
        $keys = $this->primaryKey();
1147 67
        if (empty($keys)) {
1148
            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.');
1149
        }
1150 67
        if (!$asArray && count($keys) === 1) {
1151
            return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null;
1152
        }
1153
1154 67
        $values = [];
1155 67
        foreach ($keys as $name) {
1156 67
            $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
1157
        }
1158
1159 67
        return $values;
1160
    }
1161
1162
    /**
1163
     * Populates an active record object using a row of data from the database/storage.
1164
     *
1165
     * This is an internal method meant to be called to create active record objects after
1166
     * fetching data from the database. It is mainly used by [[ActiveQuery]] to populate
1167
     * the query results into active records.
1168
     *
1169
     * When calling this method manually you should call [[afterFind()]] on the created
1170
     * record to trigger the [[EVENT_AFTER_FIND|afterFind Event]].
1171
     *
1172
     * @param BaseActiveRecord $record the record to be populated. In most cases this will be an instance
1173
     * created by [[instantiate()]] beforehand.
1174
     * @param array $row attribute values (name => value)
1175
     */
1176 316
    public static function populateRecord($record, $row)
1177
    {
1178 316
        $columns = array_flip($record->attributes());
1179 316
        foreach ($row as $name => $value) {
1180 316
            if (isset($columns[$name])) {
1181 316
                $record->_attributes[$name] = $value;
1182 6
            } elseif ($record->canSetProperty($name)) {
1183 316
                $record->$name = $value;
1184
            }
1185
        }
1186 316
        $record->_oldAttributes = $record->_attributes;
1187 316
        $record->_related = [];
1188 316
        $record->_relationsDependencies = [];
1189 316
    }
1190
1191
    /**
1192
     * Creates an active record instance.
1193
     *
1194
     * This method is called together with [[populateRecord()]] by [[ActiveQuery]].
1195
     * It is not meant to be used for creating new records directly.
1196
     *
1197
     * You may override this method if the instance being created
1198
     * depends on the row data to be populated into the record.
1199
     * For example, by creating a record based on the value of a column,
1200
     * you may implement the so-called single-table inheritance mapping.
1201
     * @param array $row row data to be populated into the record.
1202
     * @return static the newly created active record
1203
     */
1204 310
    public static function instantiate($row)
0 ignored issues
show
Unused Code introduced by
The parameter $row is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1205
    {
1206 310
        return new static();
1207
    }
1208
1209
    /**
1210
     * Returns whether there is an element at the specified offset.
1211
     * This method is required by the interface [[\ArrayAccess]].
1212
     * @param mixed $offset the offset to check on
1213
     * @return bool whether there is an element at the specified offset.
1214
     */
1215 30
    public function offsetExists($offset)
1216
    {
1217 30
        return $this->__isset($offset);
1218
    }
1219
1220
    /**
1221
     * Returns the relation object with the specified name.
1222
     * A relation is defined by a getter method which returns an [[ActiveQueryInterface]] object.
1223
     * It can be declared in either the Active Record class itself or one of its behaviors.
1224
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
1225
     * @param bool $throwException whether to throw exception if the relation does not exist.
1226
     * @return ActiveQueryInterface|ActiveQuery the relational query object. If the relation does not exist
1227
     * and `$throwException` is `false`, `null` will be returned.
1228
     * @throws InvalidArgumentException if the named relation does not exist.
1229
     */
1230 147
    public function getRelation($name, $throwException = true)
1231
    {
1232 147
        $getter = 'get' . $name;
1233
        try {
1234
            // the relation could be defined in a behavior
1235 147
            $relation = $this->$getter();
1236
        } catch (UnknownMethodException $e) {
1237
            if ($throwException) {
1238
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e);
1239
            }
1240
1241
            return null;
1242
        }
1243 147
        if (!$relation instanceof ActiveQueryInterface) {
1244
            if ($throwException) {
1245
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".');
1246
            }
1247
1248
            return null;
1249
        }
1250
1251 147
        if (method_exists($this, $getter)) {
1252
            // relation name is case sensitive, trying to validate it when the relation is defined within this class
1253 147
            $method = new \ReflectionMethod($this, $getter);
1254 147
            $realName = lcfirst(substr($method->getName(), 3));
1255 147
            if ($realName !== $name) {
1256
                if ($throwException) {
1257
                    throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($this) . " has a relation named \"$realName\" instead of \"$name\".");
1258
                }
1259
1260
                return null;
1261
            }
1262
        }
1263
1264 147
        return $relation;
1265
    }
1266
1267
    /**
1268
     * Establishes the relationship between two models.
1269
     *
1270
     * The relationship is established by setting the foreign key value(s) in one model
1271
     * to be the corresponding primary key value(s) in the other model.
1272
     * The model with the foreign key will be saved into database without performing validation.
1273
     *
1274
     * If the relationship involves a junction table, a new row will be inserted into the
1275
     * junction table which contains the primary key values from both models.
1276
     *
1277
     * Note that this method requires that the primary key value is not null.
1278
     *
1279
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1280
     * @param ActiveRecordInterface $model the model to be linked with the current one.
1281
     * @param array $extraColumns additional column values to be saved into the junction table.
1282
     * This parameter is only meaningful for a relationship involving a junction table
1283
     * (i.e., a relation set with [[ActiveRelationTrait::via()]] or [[ActiveQuery::viaTable()]].)
1284
     * @throws InvalidCallException if the method is unable to link two models.
1285
     */
1286 9
    public function link($name, $model, $extraColumns = [])
1287
    {
1288 9
        $relation = $this->getRelation($name);
1289
1290 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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1291 3
            if ($this->getIsNewRecord() || $model->getIsNewRecord()) {
1292
                throw new InvalidCallException('Unable to link models: the models being linked cannot be newly created.');
1293
            }
1294 3
            if (is_array($relation->via)) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1295
                /* @var $viaRelation ActiveQuery */
1296 3
                list($viaName, $viaRelation) = $relation->via;
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1297 3
                $viaClass = $viaRelation->modelClass;
1298
                // unset $viaName so that it can be reloaded to reflect the change
1299 3
                unset($this->_related[$viaName]);
1300
            } else {
1301
                $viaRelation = $relation->via;
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1302
                $viaTable = reset($relation->via->from);
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1303
            }
1304 3
            $columns = [];
1305 3
            foreach ($viaRelation->link as $a => $b) {
1306 3
                $columns[$a] = $this->$b;
1307
            }
1308 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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1309 3
                $columns[$b] = $model->$a;
1310
            }
1311 3
            foreach ($extraColumns as $k => $v) {
1312 3
                $columns[$k] = $v;
1313
            }
1314 3
            if (is_array($relation->via)) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1315
                /* @var $viaClass ActiveRecordInterface */
1316
                /* @var $record ActiveRecordInterface */
1317 3
                $record = Yii::createObject($viaClass);
0 ignored issues
show
Bug introduced by
The variable $viaClass does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1318 3
                foreach ($columns as $column => $value) {
1319 3
                    $record->$column = $value;
1320
                }
1321 3
                $record->insert(false);
1322
            } else {
1323
                /* @var $viaTable string */
1324
                static::getDb()->createCommand()
1325 3
                    ->insert($viaTable, $columns)->execute();
0 ignored issues
show
Bug introduced by
The variable $viaTable does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1326
            }
1327
        } else {
1328 9
            $p1 = $model->isPrimaryKey(array_keys($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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1329 9
            $p2 = static::isPrimaryKey(array_values($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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1330 9
            if ($p1 && $p2) {
1331
                if ($this->getIsNewRecord() && $model->getIsNewRecord()) {
1332
                    throw new InvalidCallException('Unable to link models: at most one model can be newly created.');
1333
                } elseif ($this->getIsNewRecord()) {
1334
                    $this->bindModels(array_flip($relation->link), $this, $model);
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1335
                } else {
1336
                    $this->bindModels($relation->link, $model, $this);
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1337
                }
1338 9
            } elseif ($p1) {
1339 3
                $this->bindModels(array_flip($relation->link), $this, $model);
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1340 9
            } elseif ($p2) {
1341 9
                $this->bindModels($relation->link, $model, $this);
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1342
            } else {
1343
                throw new InvalidCallException('Unable to link models: the link defining the relation does not involve any primary key.');
1344
            }
1345
        }
1346
1347
        // update lazily loaded related objects
1348 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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1349 3
            $this->_related[$name] = $model;
1350 9
        } elseif (isset($this->_related[$name])) {
1351 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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1352 6
                if ($relation->indexBy instanceof \Closure) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1353 3
                    $index = call_user_func($relation->indexBy, $model);
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1354
                } else {
1355 3
                    $index = $model->{$relation->indexBy};
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1356
                }
1357 6
                $this->_related[$name][$index] = $model;
1358
            } else {
1359 3
                $this->_related[$name][] = $model;
1360
            }
1361
        }
1362 9
    }
1363
1364
    /**
1365
     * Destroys the relationship between two models.
1366
     *
1367
     * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
1368
     * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
1369
     *
1370
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1371
     * @param ActiveRecordInterface $model the model to be unlinked from the current one.
1372
     * You have to make sure that the model is really related with the current model as this method
1373
     * does not check this.
1374
     * @param bool $delete whether to delete the model that contains the foreign key.
1375
     * If `false`, the model's foreign key will be set `null` and saved.
1376
     * If `true`, the model containing the foreign key will be deleted.
1377
     * @throws InvalidCallException if the models cannot be unlinked
1378
     */
1379 3
    public function unlink($name, $model, $delete = false)
1380
    {
1381 3
        $relation = $this->getRelation($name);
1382
1383 3
        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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1384 3
            if (is_array($relation->via)) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1385
                /* @var $viaRelation ActiveQuery */
1386 3
                list($viaName, $viaRelation) = $relation->via;
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1387 3
                $viaClass = $viaRelation->modelClass;
1388 3
                unset($this->_related[$viaName]);
1389
            } else {
1390 3
                $viaRelation = $relation->via;
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1391 3
                $viaTable = reset($relation->via->from);
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1392
            }
1393 3
            $columns = [];
1394 3
            foreach ($viaRelation->link as $a => $b) {
1395 3
                $columns[$a] = $this->$b;
1396
            }
1397 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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1398 3
                $columns[$b] = $model->$a;
1399
            }
1400 3
            $nulls = [];
1401 3
            foreach (array_keys($columns) as $a) {
1402 3
                $nulls[$a] = null;
1403
            }
1404 3
            if (is_array($relation->via)) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1405
                /* @var $viaClass ActiveRecordInterface */
1406 3
                if ($delete) {
1407 3
                    $viaClass::deleteAll($columns);
0 ignored issues
show
Bug introduced by
The variable $viaClass does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1408
                } else {
1409 3
                    $viaClass::updateAll($nulls, $columns);
1410
                }
1411
            } else {
1412
                /* @var $viaTable string */
1413
                /* @var $command Command */
1414 3
                $command = static::getDb()->createCommand();
1415 3
                if ($delete) {
1416
                    $command->delete($viaTable, $columns)->execute();
0 ignored issues
show
Bug introduced by
The variable $viaTable does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1417
                } else {
1418 3
                    $command->update($viaTable, $nulls, $columns)->execute();
1419
                }
1420
            }
1421
        } else {
1422 3
            $p1 = $model->isPrimaryKey(array_keys($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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1423 3
            $p2 = static::isPrimaryKey(array_values($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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1424 3
            if ($p2) {
1425 3
                if ($delete) {
1426 3
                    $model->delete();
1427
                } else {
1428 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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1429 3
                        $model->$a = null;
1430
                    }
1431 3
                    $model->save(false);
1432
                }
1433
            } elseif ($p1) {
1434
                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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1435
                    if (is_array($this->$b)) { // relation via array valued attribute
1436
                        if (($key = array_search($model->$a, $this->$b, false)) !== false) {
1437
                            $values = $this->$b;
1438
                            unset($values[$key]);
1439
                            $this->$b = array_values($values);
1440
                        }
1441
                    } else {
1442
                        $this->$b = null;
1443
                    }
1444
                }
1445
                $delete ? $this->delete() : $this->save(false);
1446
            } else {
1447
                throw new InvalidCallException('Unable to unlink models: the link does not involve any primary key.');
1448
            }
1449
        }
1450
1451 3
        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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1452
            unset($this->_related[$name]);
1453 3
        } elseif (isset($this->_related[$name])) {
1454
            /* @var $b ActiveRecordInterface */
1455 3
            foreach ($this->_related[$name] as $a => $b) {
1456 3
                if ($model->getPrimaryKey() === $b->getPrimaryKey()) {
1457 3
                    unset($this->_related[$name][$a]);
1458
                }
1459
            }
1460
        }
1461 3
    }
1462
1463
    /**
1464
     * Destroys the relationship in current model.
1465
     *
1466
     * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
1467
     * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
1468
     *
1469
     * Note that to destroy the relationship without removing records make sure your keys can be set to null
1470
     *
1471
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1472
     * @param bool $delete whether to delete the model that contains the foreign key.
1473
     *
1474
     * Note that the deletion will be performed using [[deleteAll()]], which will not trigger any events on the related models.
1475
     * If you need [[EVENT_BEFORE_DELETE]] or [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first
1476
     * and then call [[delete()]] on each of them.
1477
     */
1478 18
    public function unlinkAll($name, $delete = false)
1479
    {
1480 18
        $relation = $this->getRelation($name);
1481
1482 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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1483 9
            if (is_array($relation->via)) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1484
                /* @var $viaRelation ActiveQuery */
1485 6
                list($viaName, $viaRelation) = $relation->via;
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1486 6
                $viaClass = $viaRelation->modelClass;
1487 6
                unset($this->_related[$viaName]);
1488
            } else {
1489 3
                $viaRelation = $relation->via;
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1490 3
                $viaTable = reset($relation->via->from);
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1491
            }
1492 9
            $condition = [];
1493 9
            $nulls = [];
1494 9
            foreach ($viaRelation->link as $a => $b) {
1495 9
                $nulls[$a] = null;
1496 9
                $condition[$a] = $this->$b;
1497
            }
1498 9
            if (!empty($viaRelation->where)) {
1499
                $condition = ['and', $condition, $viaRelation->where];
1500
            }
1501 9
            if (!empty($viaRelation->on)) {
1502
                $condition = ['and', $condition, $viaRelation->on];
1503
            }
1504 9
            if (is_array($relation->via)) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1505
                /* @var $viaClass ActiveRecordInterface */
1506 6
                if ($delete) {
1507 6
                    $viaClass::deleteAll($condition);
0 ignored issues
show
Bug introduced by
The variable $viaClass does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1508
                } else {
1509 6
                    $viaClass::updateAll($nulls, $condition);
1510
                }
1511
            } else {
1512
                /* @var $viaTable string */
1513
                /* @var $command Command */
1514 3
                $command = static::getDb()->createCommand();
1515 3
                if ($delete) {
1516 3
                    $command->delete($viaTable, $condition)->execute();
0 ignored issues
show
Bug introduced by
The variable $viaTable does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1517
                } else {
1518 9
                    $command->update($viaTable, $nulls, $condition)->execute();
1519
                }
1520
            }
1521
        } else {
1522
            /* @var $relatedModel ActiveRecordInterface */
1523 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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1524 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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1525
                // relation via array valued attribute
1526
                $this->$b = [];
1527
                $this->save(false);
1528
            } else {
1529 12
                $nulls = [];
1530 12
                $condition = [];
1531 12
                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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1532 12
                    $nulls[$a] = null;
1533 12
                    $condition[$a] = $this->$b;
1534
                }
1535 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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1536 6
                    $condition = ['and', $condition, $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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1537
                }
1538 12
                if (!empty($relation->on)) {
0 ignored issues
show
Bug introduced by
Accessing on on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1539 3
                    $condition = ['and', $condition, $relation->on];
0 ignored issues
show
Bug introduced by
Accessing on on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1540
                }
1541 12
                if ($delete) {
1542 9
                    $relatedModel::deleteAll($condition);
1543
                } else {
1544 6
                    $relatedModel::updateAll($nulls, $condition);
1545
                }
1546
            }
1547
        }
1548
1549 18
        unset($this->_related[$name]);
1550 18
    }
1551
1552
    /**
1553
     * @param array $link
1554
     * @param ActiveRecordInterface $foreignModel
1555
     * @param ActiveRecordInterface $primaryModel
1556
     * @throws InvalidCallException
1557
     */
1558 9
    private function bindModels($link, $foreignModel, $primaryModel)
1559
    {
1560 9
        foreach ($link as $fk => $pk) {
1561 9
            $value = $primaryModel->$pk;
1562 9
            if ($value === null) {
1563
                throw new InvalidCallException('Unable to link models: the primary key of ' . get_class($primaryModel) . ' is null.');
1564
            }
1565 9
            if (is_array($foreignModel->$fk)) { // relation via array valued attribute
1566
                $foreignModel->$fk = array_merge($foreignModel->$fk, [$value]);
1567
            } else {
1568 9
                $foreignModel->$fk = $value;
1569
            }
1570
        }
1571 9
        $foreignModel->save(false);
1572 9
    }
1573
1574
    /**
1575
     * Returns a value indicating whether the given set of attributes represents the primary key for this model.
1576
     * @param array $keys the set of attributes to check
1577
     * @return bool whether the given set of attributes represents the primary key for this model
1578
     */
1579 15
    public static function isPrimaryKey($keys)
1580
    {
1581 15
        $pks = static::primaryKey();
1582 15
        if (count($keys) === count($pks)) {
1583 15
            return count(array_intersect($keys, $pks)) === count($pks);
1584
        }
1585
1586 9
        return false;
1587
    }
1588
1589
    /**
1590
     * Returns the text label for the specified attribute.
1591
     * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model.
1592
     * @param string $attribute the attribute name
1593
     * @return string the attribute label
1594
     * @see generateAttributeLabel()
1595
     * @see attributeLabels()
1596
     */
1597 57
    public function getAttributeLabel($attribute)
1598
    {
1599 57
        $labels = $this->attributeLabels();
1600 57
        if (isset($labels[$attribute])) {
1601 10
            return $labels[$attribute];
1602 54
        } elseif (strpos($attribute, '.')) {
1603
            $attributeParts = explode('.', $attribute);
1604
            $neededAttribute = array_pop($attributeParts);
1605
1606
            $relatedModel = $this;
1607
            foreach ($attributeParts as $relationName) {
1608
                if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
1609
                    $relatedModel = $relatedModel->$relationName;
1610
                } else {
1611
                    try {
1612
                        $relation = $relatedModel->getRelation($relationName);
1613
                    } catch (InvalidParamException $e) {
1614
                        return $this->generateAttributeLabel($attribute);
1615
                    }
1616
                    /* @var $modelClass ActiveRecordInterface */
1617
                    $modelClass = $relation->modelClass;
1618
                    $relatedModel = $modelClass::instance();
1619
                }
1620
            }
1621
1622
            $labels = $relatedModel->attributeLabels();
1623
            if (isset($labels[$neededAttribute])) {
1624
                return $labels[$neededAttribute];
1625
            }
1626
        }
1627
1628 54
        return $this->generateAttributeLabel($attribute);
1629
    }
1630
1631
    /**
1632
     * Returns the text hint for the specified attribute.
1633
     * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model.
1634
     * @param string $attribute the attribute name
1635
     * @return string the attribute hint
1636
     * @see attributeHints()
1637
     * @since 2.0.4
1638
     */
1639
    public function getAttributeHint($attribute)
1640
    {
1641
        $hints = $this->attributeHints();
1642
        if (isset($hints[$attribute])) {
1643
            return $hints[$attribute];
1644
        } elseif (strpos($attribute, '.')) {
1645
            $attributeParts = explode('.', $attribute);
1646
            $neededAttribute = array_pop($attributeParts);
1647
1648
            $relatedModel = $this;
1649
            foreach ($attributeParts as $relationName) {
1650
                if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
1651
                    $relatedModel = $relatedModel->$relationName;
1652
                } else {
1653
                    try {
1654
                        $relation = $relatedModel->getRelation($relationName);
1655
                    } catch (InvalidParamException $e) {
1656
                        return '';
1657
                    }
1658
                    /* @var $modelClass ActiveRecordInterface */
1659
                    $modelClass = $relation->modelClass;
1660
                    $relatedModel = $modelClass::instance();
1661
                }
1662
            }
1663
1664
            $hints = $relatedModel->attributeHints();
1665
            if (isset($hints[$neededAttribute])) {
1666
                return $hints[$neededAttribute];
1667
            }
1668
        }
1669
1670
        return '';
1671
    }
1672
1673
    /**
1674
     * {@inheritdoc}
1675
     *
1676
     * The default implementation returns the names of the columns whose values have been populated into this record.
1677
     */
1678
    public function fields()
1679
    {
1680
        $fields = array_keys($this->_attributes);
1681
1682
        return array_combine($fields, $fields);
1683
    }
1684
1685
    /**
1686
     * {@inheritdoc}
1687
     *
1688
     * The default implementation returns the names of the relations that have been populated into this record.
1689
     */
1690
    public function extraFields()
1691
    {
1692
        $fields = array_keys($this->getRelatedRecords());
1693
1694
        return array_combine($fields, $fields);
1695
    }
1696
1697
    /**
1698
     * Sets the element value at the specified offset to null.
1699
     * This method is required by the SPL interface [[\ArrayAccess]].
1700
     * It is implicitly called when you use something like `unset($model[$offset])`.
1701
     * @param mixed $offset the offset to unset element
1702
     */
1703 3
    public function offsetUnset($offset)
1704
    {
1705 3
        if (property_exists($this, $offset)) {
1706
            $this->$offset = null;
1707
        } else {
1708 3
            unset($this->$offset);
1709
        }
1710 3
    }
1711
1712
    /**
1713
     * Resets dependent related models checking if their links contain specific attribute.
1714
     * @param string $attribute The changed attribute name.
1715
     */
1716 15
    private function resetDependentRelations($attribute)
1717
    {
1718 15
        foreach ($this->_relationsDependencies[$attribute] as $relation) {
1719 15
            unset($this->_related[$relation]);
1720
        }
1721 15
        unset($this->_relationsDependencies[$attribute]);
1722 15
    }
1723
1724
    /**
1725
     * Sets relation dependencies for a property
1726
     * @param string $name property name
1727
     * @param ActiveQueryInterface $relation relation instance
1728
     */
1729 70
    private function setRelationDependencies($name, $relation)
1730
    {
1731 70
        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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1732 67
            foreach ($relation->link as $attribute) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1733 67
                $this->_relationsDependencies[$attribute][$name] = $name;
1734
            }
1735 39
        } elseif ($relation->via instanceof ActiveQueryInterface) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1736 15
            $this->setRelationDependencies($name, $relation->via);
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1737 27
        } elseif (is_array($relation->via)) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1738 24
            list(, $viaQuery) = $relation->via;
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
1739 24
            $this->setRelationDependencies($name, $viaQuery);
1740
        }
1741 70
    }
1742
}
1743