Completed
Push — 2.0.13-dev ( 4608bb )
by Carsten
10:19
created

BaseActiveRecord::isAttributeChanged()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.074

Importance

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