ActiveRelationTrait::indexBuckets()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 4
nop 2
dl 0
loc 12
ccs 0
cts 8
cp 0
crap 20
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use yii\base\InvalidArgumentException;
11
use yii\base\InvalidConfigException;
12
13
/**
14
 * ActiveRelationTrait implements the common methods and properties for active record relational queries.
15
 *
16
 * @author Qiang Xue <[email protected]>
17
 * @author Carsten Brandt <[email protected]>
18
 * @since 2.0
19
 * @phpcs:disable Squiz.NamingConventions.ValidVariableName.PrivateNoUnderscore
20
 *
21
 * @method ActiveRecordInterface|array|null one($db = null) See [[ActiveQueryInterface::one()]] for more info.
22
 * @method ActiveRecordInterface[] all($db = null) See [[ActiveQueryInterface::all()]] for more info.
23
 * @property ActiveRecord $modelClass
24
 */
25
trait ActiveRelationTrait
26
{
27
    /**
28
     * @var bool whether this query represents a relation to more than one record.
29
     * This property is only used in relational context. If true, this relation will
30
     * populate all query results into AR instances using [[Query::all()|all()]].
31
     * If false, only the first row of the results will be retrieved using [[Query::one()|one()]].
32
     */
33
    public $multiple;
34
    /**
35
     * @var ActiveRecord the primary model of a relational query.
36
     * This is used only in lazy loading with dynamic query options.
37
     */
38
    public $primaryModel;
39
    /**
40
     * @var array the columns of the primary and foreign tables that establish a relation.
41
     * The array keys must be columns of the table for this relation, and the array values
42
     * must be the corresponding columns from the primary table.
43
     * Do not prefix or quote the column names as this will be done automatically by Yii.
44
     * This property is only used in relational context.
45
     */
46
    public $link;
47
    /**
48
     * @var array|object the query associated with the junction table. Please call [[via()]]
49
     * to set this property instead of directly setting it.
50
     * This property is only used in relational context.
51
     * @see via()
52
     */
53
    public $via;
54
    /**
55
     * @var string the name of the relation that is the inverse of this relation.
56
     * For example, an order has a customer, which means the inverse of the "customer" relation
57
     * is the "orders", and the inverse of the "orders" relation is the "customer".
58
     * If this property is set, the primary record(s) will be referenced through the specified relation.
59
     * For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
60
     * and accessing the customer of an order will not trigger new DB query.
61
     * This property is only used in relational context.
62
     * @see inverseOf()
63
     */
64
    public $inverseOf;
65
66
    private $viaMap;
67
68
    /**
69
     * Clones internal objects.
70
     */
71 1
    public function __clone()
72
    {
73 1
        parent::__clone();
74
        // make a clone of "via" object so that the same query object can be reused multiple times
75 1
        if (is_object($this->via)) {
76
            $this->via = clone $this->via;
77 1
        } elseif (is_array($this->via)) {
0 ignored issues
show
introduced by
The condition is_array($this->via) is always true.
Loading history...
78
            $this->via = [$this->via[0], clone $this->via[1], $this->via[2]];
79
        }
80
    }
81
82
    /**
83
     * Specifies the relation associated with the junction table.
84
     *
85
     * Use this method to specify a pivot record/table when declaring a relation in the [[ActiveRecord]] class:
86
     *
87
     * ```php
88
     * class Order extends ActiveRecord
89
     * {
90
     *    public function getOrderItems() {
91
     *        return $this->hasMany(OrderItem::class, ['order_id' => 'id']);
92
     *    }
93
     *
94
     *    public function getItems() {
95
     *        return $this->hasMany(Item::class, ['id' => 'item_id'])
96
     *                    ->via('orderItems');
97
     *    }
98
     * }
99
     * ```
100
     *
101
     * @param string $relationName the relation name. This refers to a relation declared in [[primaryModel]].
102
     * @param callable|null $callable a PHP callback for customizing the relation associated with the junction table.
103
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
104
     * @return $this the relation object itself.
105
     */
106
    public function via($relationName, ?callable $callable = null)
107
    {
108
        $relation = $this->primaryModel->getRelation($relationName);
109
        $callableUsed = $callable !== null;
110
        $this->via = [$relationName, $relation, $callableUsed];
111
        if ($callable !== null) {
112
            call_user_func($callable, $relation);
113
        }
114
115
        return $this;
116
    }
117
118
    /**
119
     * Sets the name of the relation that is the inverse of this relation.
120
     * For example, a customer has orders, which means the inverse of the "orders" relation is the "customer".
121
     * If this property is set, the primary record(s) will be referenced through the specified relation.
122
     * For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
123
     * and accessing the customer of an order will not trigger a new DB query.
124
     *
125
     * Use this method when declaring a relation in the [[ActiveRecord]] class, e.g. in Customer model:
126
     *
127
     * ```php
128
     * public function getOrders()
129
     * {
130
     *     return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer');
131
     * }
132
     * ```
133
     *
134
     * This also may be used for Order model, but with caution:
135
     *
136
     * ```php
137
     * public function getCustomer()
138
     * {
139
     *     return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders');
140
     * }
141
     * ```
142
     *
143
     * in this case result will depend on how order(s) was loaded.
144
     * Let's suppose customer has several orders. If only one order was loaded:
145
     *
146
     * ```php
147
     * $orders = Order::find()->where(['id' => 1])->all();
148
     * $customerOrders = $orders[0]->customer->orders;
149
     * ```
150
     *
151
     * variable `$customerOrders` will contain only one order. If orders was loaded like this:
152
     *
153
     * ```php
154
     * $orders = Order::find()->with('customer')->where(['customer_id' => 1])->all();
155
     * $customerOrders = $orders[0]->customer->orders;
156
     * ```
157
     *
158
     * variable `$customerOrders` will contain all orders of the customer.
159
     *
160
     * @param string $relationName the name of the relation that is the inverse of this relation.
161
     * @return $this the relation object itself.
162
     */
163
    public function inverseOf($relationName)
164
    {
165
        $this->inverseOf = $relationName;
166
        return $this;
167
    }
168
169
    /**
170
     * Finds the related records for the specified primary record.
171
     * This method is invoked when a relation of an ActiveRecord is being accessed lazily.
172
     * @param string $name the relation name
173
     * @param ActiveRecordInterface|BaseActiveRecord $model the primary model
174
     * @return mixed the related record(s)
175
     * @throws InvalidArgumentException if the relation is invalid
176
     */
177 1
    public function findFor($name, $model)
178
    {
179 1
        if (method_exists($model, 'get' . $name)) {
180 1
            $method = new \ReflectionMethod($model, 'get' . $name);
181 1
            $realName = lcfirst(substr($method->getName(), 3));
182 1
            if ($realName !== $name) {
183
                throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($model) . " has a relation named \"$realName\" instead of \"$name\".");
184
            }
185
        }
186
187 1
        return $this->multiple ? $this->all() : $this->one();
0 ignored issues
show
Bug introduced by
It seems like one() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

187
        return $this->multiple ? $this->all() : $this->/** @scrutinizer ignore-call */ one();
Loading history...
Bug introduced by
It seems like all() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

187
        return $this->multiple ? $this->/** @scrutinizer ignore-call */ all() : $this->one();
Loading history...
188
    }
189
190
    /**
191
     * If applicable, populate the query's primary model into the related records' inverse relationship.
192
     * @param array $result the array of related records as generated by [[populate()]]
193
     * @since 2.0.9
194
     */
195
    private function addInverseRelations(&$result)
196
    {
197
        if ($this->inverseOf === null) {
198
            return;
199
        }
200
201
        foreach ($result as $i => $relatedModel) {
202
            if ($relatedModel instanceof ActiveRecordInterface) {
203
                if (!isset($inverseRelation)) {
204
                    $inverseRelation = $relatedModel->getRelation($this->inverseOf);
205
                }
206
                $relatedModel->populateRelation($this->inverseOf, $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel);
207
            } else {
208
                if (!isset($inverseRelation)) {
209
                    /** @var ActiveRecordInterface $modelClass */
210
                    $modelClass = $this->modelClass;
211
                    $inverseRelation = $modelClass::instance()->getRelation($this->inverseOf);
212
                }
213
                $result[$i][$this->inverseOf] = $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel;
214
            }
215
        }
216
    }
217
218
    /**
219
     * Finds the related records and populates them into the primary models.
220
     * @param string $name the relation name
221
     * @param array $primaryModels primary models
222
     * @return array the related models
223
     * @throws InvalidConfigException if [[link]] is invalid
224
     */
225
    public function populateRelation($name, &$primaryModels)
226
    {
227
        if (!is_array($this->link)) {
0 ignored issues
show
introduced by
The condition is_array($this->link) is always true.
Loading history...
228
            throw new InvalidConfigException('Invalid link: it must be an array of key-value pairs.');
229
        }
230
231
        if ($this->via instanceof self) {
232
            // via junction table
233
            /** @var self $viaQuery */
234
            $viaQuery = $this->via;
235
            $viaModels = $viaQuery->findJunctionRows($primaryModels);
236
            $this->filterByModels($viaModels);
237
        } elseif (is_array($this->via)) {
238
            // via relation
239
            /** @var self|ActiveQueryTrait $viaQuery */
240
            list($viaName, $viaQuery) = $this->via;
241
            if ($viaQuery->asArray === null) {
242
                // inherit asArray from primary query
243
                $viaQuery->asArray($this->asArray);
0 ignored issues
show
Bug introduced by
It seems like asArray() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

243
                $viaQuery->/** @scrutinizer ignore-call */ 
244
                           asArray($this->asArray);
Loading history...
244
            }
245
            $viaQuery->primaryModel = null;
0 ignored issues
show
Bug Best Practice introduced by
The property primaryModel does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
246
            $viaModels = array_filter($viaQuery->populateRelation($viaName, $primaryModels));
0 ignored issues
show
Bug introduced by
It seems like populateRelation() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

246
            $viaModels = array_filter($viaQuery->/** @scrutinizer ignore-call */ populateRelation($viaName, $primaryModels));
Loading history...
247
            $this->filterByModels($viaModels);
248
        } else {
249
            $this->filterByModels($primaryModels);
250
        }
251
252
        if (!$this->multiple && count($primaryModels) === 1) {
253
            $model = $this->one();
254
            $primaryModel = reset($primaryModels);
255
            if ($primaryModel instanceof ActiveRecordInterface) {
256
                $primaryModel->populateRelation($name, $model);
257
            } else {
258
                $primaryModels[key($primaryModels)][$name] = $model;
259
            }
260
            if ($this->inverseOf !== null) {
261
                $this->populateInverseRelation($primaryModels, [$model], $name, $this->inverseOf);
262
            }
263
264
            return [$model];
265
        }
266
267
        // https://github.com/yiisoft/yii2/issues/3197
268
        // delay indexing related models after buckets are built
269
        $indexBy = $this->indexBy;
270
        $this->indexBy = null;
0 ignored issues
show
Bug Best Practice introduced by
The property indexBy does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
271
        $models = $this->all();
272
273
        if (isset($viaModels, $viaQuery)) {
274
            $buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery);
275
        } else {
276
            $buckets = $this->buildBuckets($models, $this->link);
277
        }
278
279
        $this->indexBy = $indexBy;
280
        if ($this->indexBy !== null && $this->multiple) {
281
            $buckets = $this->indexBuckets($buckets, $this->indexBy);
282
        }
283
284
        $link = array_values($this->link);
285
        if (isset($viaQuery)) {
286
            $deepViaQuery = $viaQuery;
287
            while ($deepViaQuery->via) {
288
                $deepViaQuery = is_array($deepViaQuery->via) ? $deepViaQuery->via[1] : $deepViaQuery->via;
289
            };
290
            $link = array_values($deepViaQuery->link);
291
        }
292
        foreach ($primaryModels as $i => $primaryModel) {
293
            $keys = null;
294
            if ($this->multiple && count($link) === 1) {
295
                $primaryModelKey = reset($link);
296
                $keys = isset($primaryModel[$primaryModelKey]) ? $primaryModel[$primaryModelKey] : null;
297
            }
298
            if (is_array($keys)) {
299
                $value = [];
300
                foreach ($keys as $key) {
301
                    $key = $this->normalizeModelKey($key);
302
                    if (isset($buckets[$key])) {
303
                        if ($this->indexBy !== null) {
304
                            // if indexBy is set, array_merge will cause renumbering of numeric array
305
                            foreach ($buckets[$key] as $bucketKey => $bucketValue) {
306
                                $value[$bucketKey] = $bucketValue;
307
                            }
308
                        } else {
309
                            $value = array_merge($value, $buckets[$key]);
310
                        }
311
                    }
312
                }
313
            } else {
314
                $key = $this->getModelKey($primaryModel, $link);
315
                $value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? [] : null);
316
            }
317
            if ($primaryModel instanceof ActiveRecordInterface) {
318
                $primaryModel->populateRelation($name, $value);
319
            } else {
320
                $primaryModels[$i][$name] = $value;
321
            }
322
        }
323
        if ($this->inverseOf !== null) {
324
            $this->populateInverseRelation($primaryModels, $models, $name, $this->inverseOf);
325
        }
326
327
        return $models;
328
    }
329
330
    /**
331
     * @param ActiveRecordInterface[] $primaryModels primary models
332
     * @param ActiveRecordInterface[] $models models
333
     * @param string $primaryName the primary relation name
334
     * @param string $name the relation name
335
     */
336
    private function populateInverseRelation(&$primaryModels, $models, $primaryName, $name)
337
    {
338
        if (empty($models) || empty($primaryModels)) {
339
            return;
340
        }
341
        $model = reset($models);
342
        /** @var ActiveQueryInterface|ActiveQuery $relation */
343
        if ($model instanceof ActiveRecordInterface) {
344
            $relation = $model->getRelation($name);
345
        } else {
346
            /** @var ActiveRecordInterface $modelClass */
347
            $modelClass = $this->modelClass;
348
            $relation = $modelClass::instance()->getRelation($name);
349
        }
350
351
        if ($relation->multiple) {
352
            $buckets = $this->buildBuckets($primaryModels, $relation->link, null, null, false);
353
            if ($model instanceof ActiveRecordInterface) {
354
                foreach ($models as $model) {
355
                    $key = $this->getModelKey($model, $relation->link);
356
                    $model->populateRelation($name, isset($buckets[$key]) ? $buckets[$key] : []);
357
                }
358
            } else {
359
                foreach ($primaryModels as $i => $primaryModel) {
360
                    if ($this->multiple) {
361
                        foreach ($primaryModel as $j => $m) {
362
                            $key = $this->getModelKey($m, $relation->link);
363
                            $primaryModels[$i][$j][$name] = isset($buckets[$key]) ? $buckets[$key] : [];
364
                        }
365
                    } elseif (!empty($primaryModel[$primaryName])) {
366
                        $key = $this->getModelKey($primaryModel[$primaryName], $relation->link);
367
                        $primaryModels[$i][$primaryName][$name] = isset($buckets[$key]) ? $buckets[$key] : [];
368
                    }
369
                }
370
            }
371
        } elseif ($this->multiple) {
372
            foreach ($primaryModels as $i => $primaryModel) {
373
                foreach ($primaryModel[$primaryName] as $j => $m) {
374
                    if ($m instanceof ActiveRecordInterface) {
375
                        $m->populateRelation($name, $primaryModel);
376
                    } else {
377
                        $primaryModels[$i][$primaryName][$j][$name] = $primaryModel;
378
                    }
379
                }
380
            }
381
        } else {
382
            foreach ($primaryModels as $i => $primaryModel) {
383
                if ($primaryModels[$i][$primaryName] instanceof ActiveRecordInterface) {
384
                    $primaryModels[$i][$primaryName]->populateRelation($name, $primaryModel);
385
                } elseif (!empty($primaryModels[$i][$primaryName])) {
386
                    $primaryModels[$i][$primaryName][$name] = $primaryModel;
387
                }
388
            }
389
        }
390
    }
391
392
    /**
393
     * @param array $models
394
     * @param array $link
395
     * @param array|null $viaModels
396
     * @param self|null $viaQuery
397
     * @param bool $checkMultiple
398
     * @return array
399
     */
400
    private function buildBuckets($models, $link, $viaModels = null, $viaQuery = null, $checkMultiple = true)
401
    {
402
        if ($viaModels !== null) {
403
            $map = [];
404
            $viaLink = $viaQuery->link;
405
            $viaLinkKeys = array_keys($viaLink);
406
            $linkValues = array_values($link);
407
            foreach ($viaModels as $viaModel) {
408
                $key1 = $this->getModelKey($viaModel, $viaLinkKeys);
409
                $key2 = $this->getModelKey($viaModel, $linkValues);
410
                $map[$key2][$key1] = true;
411
            }
412
413
            $viaQuery->viaMap = $map;
414
415
            $viaVia = $viaQuery->via;
416
            while ($viaVia) {
417
                $viaViaQuery = is_array($viaVia) ? $viaVia[1] : $viaVia;
418
                $map = $this->mapVia($map, $viaViaQuery->viaMap);
419
420
                $viaVia = $viaViaQuery->via;
421
            };
422
        }
423
424
        $buckets = [];
425
        $linkKeys = array_keys($link);
426
427
        if (isset($map)) {
428
            foreach ($models as $model) {
429
                $key = $this->getModelKey($model, $linkKeys);
430
                if (isset($map[$key])) {
431
                    foreach (array_keys($map[$key]) as $key2) {
432
                        $buckets[$key2][] = $model;
433
                    }
434
                }
435
            }
436
        } else {
437
            foreach ($models as $model) {
438
                $key = $this->getModelKey($model, $linkKeys);
439
                $buckets[$key][] = $model;
440
            }
441
        }
442
443
        if ($checkMultiple && !$this->multiple) {
444
            foreach ($buckets as $i => $bucket) {
445
                $buckets[$i] = reset($bucket);
446
            }
447
        }
448
449
        return $buckets;
450
    }
451
452
    /**
453
     * @param array $map
454
     * @param array $viaMap
455
     * @return array
456
     */
457
    private function mapVia($map, $viaMap)
458
    {
459
        $resultMap = [];
460
        foreach ($map as $key => $linkKeys) {
461
            $resultMap[$key] = [];
462
            foreach (array_keys($linkKeys) as $linkKey) {
463
                $resultMap[$key] += $viaMap[$linkKey];
464
            }
465
        }
466
        return $resultMap;
467
    }
468
469
    /**
470
     * Indexes buckets by column name.
471
     *
472
     * @param array $buckets
473
     * @param string|callable $indexBy the name of the column by which the query results should be indexed by.
474
     * This can also be a callable (e.g. anonymous function) that returns the index value based on the given row data.
475
     * @return array
476
     */
477
    private function indexBuckets($buckets, $indexBy)
478
    {
479
        $result = [];
480
        foreach ($buckets as $key => $models) {
481
            $result[$key] = [];
482
            foreach ($models as $model) {
483
                $index = is_string($indexBy) ? $model[$indexBy] : call_user_func($indexBy, $model);
484
                $result[$key][$index] = $model;
485
            }
486
        }
487
488
        return $result;
489
    }
490
491
    /**
492
     * @param array $attributes the attributes to prefix
493
     * @return array
494
     */
495 1
    private function prefixKeyColumns($attributes)
496
    {
497 1
        if ($this instanceof ActiveQuery && (!empty($this->join) || !empty($this->joinWith))) {
498
            if (empty($this->from)) {
499
                /** @var ActiveRecord $modelClass */
500
                $modelClass = $this->modelClass;
501
                $alias = $modelClass::tableName();
502
            } else {
503
                foreach ($this->from as $alias => $table) {
504
                    if (!is_string($alias)) {
505
                        $alias = $table;
506
                    }
507
                    break;
508
                }
509
            }
510
            if (isset($alias)) {
511
                foreach ($attributes as $i => $attribute) {
512
                    $attributes[$i] = "$alias.$attribute";
513
                }
514
            }
515
        }
516
517 1
        return $attributes;
518
    }
519
520
    /**
521
     * @param array $models
522
     */
523 1
    private function filterByModels($models)
524
    {
525 1
        $attributes = array_keys($this->link);
526
527 1
        $attributes = $this->prefixKeyColumns($attributes);
528
529 1
        $values = [];
530 1
        if (count($attributes) === 1) {
531
            // single key
532 1
            $attribute = reset($this->link);
533 1
            foreach ($models as $model) {
534 1
                $value = isset($model[$attribute]) || (is_object($model) && property_exists($model, $attribute)) ? $model[$attribute] : null;
535 1
                if ($value !== null) {
536 1
                    if (is_array($value)) {
537
                        $values = array_merge($values, $value);
538 1
                    } elseif ($value instanceof ArrayExpression && $value->getDimension() === 1) {
539
                        $values = array_merge($values, $value->getValue());
0 ignored issues
show
Bug introduced by
It seems like $value->getValue() can also be of type yii\db\QueryInterface; however, parameter $arrays of array_merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

539
                        $values = array_merge($values, /** @scrutinizer ignore-type */ $value->getValue());
Loading history...
540
                    } else {
541 1
                        $values[] = $value;
542
                    }
543
                }
544
            }
545 1
            if (empty($values)) {
546 1
                $this->emulateExecution();
0 ignored issues
show
Bug introduced by
It seems like emulateExecution() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

546
                $this->/** @scrutinizer ignore-call */ 
547
                       emulateExecution();
Loading history...
547
            }
548
        } else {
549
            // composite keys
550
551
            // ensure keys of $this->link are prefixed the same way as $attributes
552
            $prefixedLink = array_combine($attributes, $this->link);
553
            foreach ($models as $model) {
554
                $v = [];
555
                foreach ($prefixedLink as $attribute => $link) {
556
                    $v[$attribute] = $model[$link];
557
                }
558
                $values[] = $v;
559
                if (empty($v)) {
560
                    $this->emulateExecution();
561
                }
562
            }
563
        }
564
565 1
        if (!empty($values)) {
566 1
            $scalarValues = [];
567 1
            $nonScalarValues = [];
568 1
            foreach ($values as $value) {
569 1
                if (is_scalar($value)) {
570 1
                    $scalarValues[] = $value;
571
                } else {
572
                    $nonScalarValues[] = $value;
573
                }
574
            }
575
576 1
            $scalarValues = array_unique($scalarValues);
577 1
            $values = array_merge($scalarValues, $nonScalarValues);
578
        }
579
580 1
        $this->andWhere(['in', $attributes, $values]);
0 ignored issues
show
Bug introduced by
It seems like andWhere() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

580
        $this->/** @scrutinizer ignore-call */ 
581
               andWhere(['in', $attributes, $values]);
Loading history...
581
    }
582
583
    /**
584
     * @param ActiveRecordInterface|array $model
585
     * @param array $attributes
586
     * @return string|false
587
     */
588
    private function getModelKey($model, $attributes)
589
    {
590
        $key = [];
591
        foreach ($attributes as $attribute) {
592
            if (isset($model[$attribute]) || (is_object($model) && property_exists($model, $attribute))) {
593
                $key[] = $this->normalizeModelKey($model[$attribute]);
594
            }
595
        }
596
        if (count($key) > 1) {
597
            return serialize($key);
598
        }
599
        return reset($key);
600
    }
601
602
    /**
603
     * @param mixed $value raw key value. Since 2.0.40 non-string values must be convertible to string (like special
604
     * objects for cross-DBMS relations, for example: `|MongoId`).
605
     * @return string normalized key value.
606
     */
607
    private function normalizeModelKey($value)
608
    {
609
        try {
610
            return (string)$value;
611
        } catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $e) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
612
            throw new InvalidConfigException('Value must be convertable to string.');
613
        } catch (\Throwable $e) {
614
            throw new InvalidConfigException('Value must be convertable to string.');
615
        }
616
    }
617
618
    /**
619
     * @param array $primaryModels either array of AR instances or arrays
620
     * @return array
621
     */
622
    private function findJunctionRows($primaryModels)
623
    {
624
        if (empty($primaryModels)) {
625
            return [];
626
        }
627
        $this->filterByModels($primaryModels);
628
        /** @var ActiveRecord $primaryModel */
629
        $primaryModel = reset($primaryModels);
630
        if (!$primaryModel instanceof ActiveRecordInterface) {
0 ignored issues
show
introduced by
$primaryModel is always a sub-type of yii\db\ActiveRecordInterface.
Loading history...
631
            // when primaryModels are array of arrays (asArray case)
632
            $primaryModel = $this->modelClass;
633
        }
634
635
        return $this->asArray()->all($primaryModel::getDb());
636
    }
637
}
638