Passed
Push — master ( d8fa21...b52db3 )
by Sergei
02:45
created

ActiveRelationTrait::getPrimaryModel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
ccs 1
cts 1
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\ActiveRecord;
6
7
use Closure;
8
use ReflectionException;
9
use Stringable;
10
use Throwable;
11
use Yiisoft\Db\Exception\Exception;
12
use Yiisoft\Db\Exception\InvalidArgumentException;
13
use Yiisoft\Db\Exception\InvalidConfigException;
14
use Yiisoft\Db\Exception\NotSupportedException;
15
16
use function array_combine;
17
use function array_diff_key;
18
use function array_fill_keys;
19
use function array_filter;
20
use function array_intersect_key;
21
use function array_keys;
22
use function array_merge;
23
use function array_unique;
24
use function count;
25
use function is_array;
26
use function is_object;
27
use function is_scalar;
28
use function is_string;
29
use function key;
30
use function reset;
31
use function serialize;
32
33
/**
34
 * ActiveRelationTrait implements the common methods and properties for active record relational queries.
35
 */
36
trait ActiveRelationTrait
37
{
38
    private bool $multiple = false;
39
    private ActiveRecordInterface|null $primaryModel = null;
40
    /** @psalm-var string[] */
41
    private array $link = [];
42
    /**
43
     * @var string|null the name of the relation that is the inverse of this relation.
44
     *
45
     * For example, an order has a customer, which means the inverse of the "customer" relation is the "orders", and the
46
     * inverse of the "orders" relation is the "customer". If this property is set, the primary record(s) will be
47
     * referenced through the specified relation.
48
     *
49
     * For example, `$customer->orders[0]->customer` and `$customer` will be the same object, and accessing the customer
50
     * of an order will not trigger new DB query.
51
     *
52
     * This property is only used in relational context.
53
     *
54
     * {@see inverseOf()}
55
     */
56
    private string|null $inverseOf = null;
57
    private array|ActiveQuery|null $via = null;
58
    private array $viaMap = [];
59
60
    /**
61
     * Clones internal objects.
62
     */
63
    public function __clone()
64
    {
65
        /** make a clone of "via" object so that the same query object can be reused multiple times */
66
        if (is_object($this->via)) {
67
            $this->via = clone $this->via;
68
        } elseif (is_array($this->via)) {
69
            $this->via = [$this->via[0], clone $this->via[1], $this->via[2]];
70
        }
71
    }
72
73
    /**
74
     * Specifies the relation associated with the junction table.
75
     *
76
     * Use this method to specify a pivot record/table when declaring a relation in the {@see ActiveRecord} class:
77
     *
78
     * ```php
79
     * class Order extends ActiveRecord
80
     * {
81
     *    public function getOrderItems() {
82
     *        return $this->hasMany(OrderItem::class, ['order_id' => 'id']);
83
     *    }
84
     *
85
     *    public function getItems() {
86
     *        return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems');
87
     *    }
88
     * }
89
     * ```
90
     *
91
     * @param string $relationName the relation name. This refers to a relation declared in {@see primaryModel}.
92
     * @param callable|null $callable a PHP callback for customizing the relation associated with the junction table.
93
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
94
     *
95
     * @return static the relation object itself.
96
     */
97
    public function via(string $relationName, callable $callable = null): static
98
    {
99
        $relation = $this->primaryModel?->relationQuery($relationName);
100
        $callableUsed = $callable !== null;
101
        $this->via = [$relationName, $relation, $callableUsed];
102 107
103
        if ($callableUsed) {
104 107
            $callable($relation);
105 107
        }
106 107
107
        return $this;
108 107
    }
109 73
110
    /**
111
     * Sets the name of the relation that is the inverse of this relation.
112 107
     *
113
     * For example, a customer has orders, which means the inverse of the "orders" relation is the "customer".
114
     *
115
     * If this property is set, the primary record(s) will be referenced through the specified relation.
116
     *
117
     * For example, `$customer->orders[0]->customer` and `$customer` will be the same object, and accessing the customer
118
     * of an order will not trigger a new DB query.
119
     *
120
     * Use this method when declaring a relation in the {@see ActiveRecord} class, e.g. in Customer model:
121
     *
122
     * ```php
123
     * public function getOrders()
124
     * {
125
     *     return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer');
126
     * }
127
     * ```
128
     *
129
     * This also may be used for Order model, but with caution:
130
     *
131
     * ```php
132
     * public function getCustomer()
133
     * {
134
     *     return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders');
135
     * }
136
     * ```
137
     *
138
     * in this case result will depend on how order(s) was loaded.
139
     * Let's suppose customer has several orders. If only one order was loaded:
140
     *
141
     * ```php
142
     * $orderQuery = new ActiveQuery(Order::class, $db);
143
     * $orders = $orderQuery->where(['id' => 1])->all();
144
     * $customerOrders = $orders[0]->customer->orders;
145
     * ```
146
     *
147
     * variable `$customerOrders` will contain only one order. If orders was loaded like this:
148
     *
149
     * ```php
150
     * $orderQuery = new ActiveQuery(Order::class, $db);
151
     * $orders = $orderQuery->with('customer')->where(['customer_id' => 1])->all();
152
     * $customerOrders = $orders[0]->customer->orders;
153
     * ```
154
     *
155
     * variable `$customerOrders` will contain all orders of the customer.
156
     *
157
     * @param string $relationName the name of the relation that is the inverse of this relation.
158
     *
159
     * @return static the relation object itself.
160
     */
161
    public function inverseOf(string $relationName): static
162
    {
163
        $this->inverseOf = $relationName;
164
165
        return $this;
166 16
    }
167
168 16
    /**
169
     * Returns query records depends on {@see $multiple} .
170 16
     *
171
     * This method is invoked when a relation of an ActiveRecord is being accessed in a lazy fashion.
172
     *
173
     * @throws Exception
174
     * @throws InvalidArgumentException
175
     * @throws InvalidConfigException
176
     * @throws ReflectionException
177
     * @throws Throwable if the relation is invalid.
178
     *
179
     * @return ActiveRecordInterface|array|null the related record(s).
180
     */
181
    public function relatedRecords(): ActiveRecordInterface|array|null
182
    {
183
        return $this->multiple ? $this->all() : $this->onePopulate();
0 ignored issues
show
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

183
        return $this->multiple ? $this->/** @scrutinizer ignore-call */ all() : $this->onePopulate();
Loading history...
Bug introduced by
It seems like onePopulate() 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

183
        return $this->multiple ? $this->all() : $this->/** @scrutinizer ignore-call */ onePopulate();
Loading history...
184
    }
185
186 101
    /**
187
     * If applicable, populate the query's primary model into the related records' inverse relationship.
188 101
     *
189 101
     * @param array $result the array of related records as generated by {@see populate()}
190 101
     *
191 101
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
192
     */
193
    private function addInverseRelations(array &$result): void
194
    {
195
        if ($this->inverseOf === null) {
196
            return;
197
        }
198
199 101
        $relatedModel = reset($result);
200
201
        if ($relatedModel instanceof ActiveRecordInterface) {
202
            $inverseRelation = $relatedModel->relationQuery($this->inverseOf);
203
            $primaryModel = $inverseRelation->getMultiple() ? [$this->primaryModel] : $this->primaryModel;
204
205
            foreach ($result as $relatedModel) {
206
                $relatedModel->populateRelation($this->inverseOf, $primaryModel);
207 16
            }
208
        } else {
209 16
            $inverseRelation = $this->getARInstance()->relationQuery($this->inverseOf);
0 ignored issues
show
Bug introduced by
It seems like getARInstance() 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

209
            $inverseRelation = $this->/** @scrutinizer ignore-call */ getARInstance()->relationQuery($this->inverseOf);
Loading history...
210
            $primaryModel = $inverseRelation->getMultiple() ? [$this->primaryModel] : $this->primaryModel;
211
212
            foreach ($result as &$relatedModel) {
213 16
                $relatedModel[$this->inverseOf] = $primaryModel;
214 16
            }
215 16
        }
216 16
    }
217
218 16
    /**
219 16
     * Finds the related records and populates them into the primary models.
220 16
     *
221
     * @param string $name the relation name
222
     * @param array $primaryModels primary models
223 8
     *
224 8
     * @throws InvalidArgumentException|InvalidConfigException|NotSupportedException|Throwable if {@see link()} is
225
     * invalid.
226
     * @throws Exception
227 8
     *
228 8
     * @return array the related models
229
     */
230
    public function populateRelation(string $name, array &$primaryModels): array
231 16
    {
232
        if ($this->via instanceof self) {
233
            $viaQuery = $this->via;
234
            $viaModels = $viaQuery->findJunctionRows($primaryModels);
235
            $this->filterByModels($viaModels);
236
        } elseif (is_array($this->via)) {
237
            [$viaName, $viaQuery] = $this->via;
238
239
            if ($viaQuery->asArray === null) {
240
                /** inherit asArray from primary query */
241
                $viaQuery->asArray($this->asArray);
242
            }
243
244
            $viaQuery->primaryModel = null;
245 139
            $viaModels = $viaQuery->populateRelation($viaName, $primaryModels);
246
            $this->filterByModels($viaModels);
247 139
        } else {
248
            $this->filterByModels($primaryModels);
249
        }
250
251 139
        if (!$this->multiple && count($primaryModels) === 1) {
252
            $model = $this->onePopulate();
253
            $primaryModel = reset($primaryModels);
254
255
            if ($primaryModel instanceof ActiveRecordInterface) {
256
                $primaryModel->populateRelation($name, $model);
257 12
            } else {
258 12
                $primaryModels[key($primaryModels)][$name] = $model;
259 12
            }
260 139
261
            if ($this->inverseOf !== null) {
262
                $this->populateInverseRelation($primaryModels, [$model], $name, $this->inverseOf);
263
            }
264
265
            return [$model];
266 72
        }
267
268 72
        /**
269
         * {@see https://github.com/yiisoft/yii2/issues/3197}
270 72
         *
271
         * delay indexing related models after buckets are built.
272
         */
273 72
        $indexBy = $this->getIndexBy();
0 ignored issues
show
Bug introduced by
It seems like getIndexBy() 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

273
        /** @scrutinizer ignore-call */ 
274
        $indexBy = $this->getIndexBy();
Loading history...
274 72
        $this->indexBy(null);
0 ignored issues
show
Bug introduced by
It seems like indexBy() 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

274
        $this->/** @scrutinizer ignore-call */ 
275
               indexBy(null);
Loading history...
275 72
        $models = $this->all();
276
277 139
        if (isset($viaModels, $viaQuery)) {
278
            $buckets = $this->buildBuckets($models, $viaModels, $viaQuery);
279
        } else {
280 139
            $buckets = $this->buildBuckets($models);
281 28
        }
282 28
283
        $this->indexBy($indexBy);
284 28
285 28
        if ($indexBy !== null && $this->multiple) {
286
            $buckets = $this->indexBuckets($buckets, $indexBy);
287 4
        }
288
289
        if (isset($viaQuery)) {
290 28
            $deepViaQuery = $viaQuery;
291 8
292
            while ($deepViaQuery->via) {
293
                $deepViaQuery = is_array($deepViaQuery->via) ? $deepViaQuery->via[1] : $deepViaQuery->via;
294 28
            }
295
296
            $link = $deepViaQuery->link;
297
        } else {
298
            $link = $this->link;
299
        }
300
301
        foreach ($primaryModels as $i => $primaryModel) {
302 123
            $keys = null;
303 123
304 123
            if ($this->multiple && count($link) === 1) {
305
                $primaryModelKey = reset($link);
306 123
307 72
                if ($primaryModel instanceof ActiveRecordInterface) {
308
                    $keys = $primaryModel->getAttribute($primaryModelKey);
309 123
                } else {
310
                    $keys = $primaryModel[$primaryModelKey] ?? null;
311
                }
312 123
            }
313
314 123
            if (is_array($keys)) {
315 17
                $value = [];
316
317
                foreach ($keys as $key) {
318 123
                    $key = $this->normalizeModelKey($key);
319 123
                    if (isset($buckets[$key])) {
320 72
                        $value[] = $buckets[$key];
321
                    }
322 72
                }
323 5
324
                if ($indexBy !== null) {
325
                    /** if indexBy is set, array_merge will cause renumbering of numeric array */
326 72
                    $value = array_replace(...$value);
327
                } else {
328
                    $value = array_merge(...$value);
329 123
                }
330 123
            } else {
331
                $key = $this->getModelKey($primaryModel, $link);
332
                $value = $buckets[$key] ?? ($this->multiple ? [] : null);
333
            }
334
335
            if ($primaryModel instanceof ActiveRecordInterface) {
336
                $primaryModel->populateRelation($name, $value);
337
            } else {
338
                $primaryModels[$i][$name] = $value;
339
            }
340
        }
341
342
        if ($this->inverseOf !== null) {
343
            $this->populateInverseRelation($primaryModels, $models, $name, $this->inverseOf);
344
        }
345
346 123
        return $models;
347 123
    }
348
349
    /**
350 123
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
351 123
     */
352
    private function populateInverseRelation(
353 9
        array &$primaryModels,
354
        array $models,
355
        string $primaryName,
356 123
        string $name
357 8
    ): void {
358
        if (empty($models) || empty($primaryModels)) {
359
            return;
360 123
        }
361
362
        $model = reset($models);
363 12
364
        if ($model instanceof ActiveRecordInterface) {
365
            $this->populateInverseRelationToModels($models, $primaryModels, $name);
366
            return;
367
        }
368
369 12
        $primaryModel = reset($primaryModels);
370
371
        if ($primaryModel instanceof ActiveRecordInterface) {
372 12
            if ($this->multiple) {
373
                foreach ($primaryModels as $primaryModel) {
374
                    $models = $primaryModel->relation($primaryName);
375 12
                    if (!empty($models)) {
376 12
                        $this->populateInverseRelationToModels($models, $primaryModels, $name);
377
                        $primaryModel->populateRelation($primaryName, $models);
378 4
                    }
379
                }
380
            } else {
381 12
                foreach ($primaryModels as $primaryModel) {
382 8
                    $model = $primaryModel->relation($primaryName);
383 8
                    if (!empty($model)) {
384 8
                        $models = [$model];
385 8
                        $this->populateInverseRelationToModels($models, $primaryModels, $name);
386 8
                        $primaryModel->populateRelation($primaryName, $models[0]);
387
                    }
388
                }
389 8
            }
390 4
        } else {
391
            if ($this->multiple) {
392
                foreach ($primaryModels as &$primaryModel) {
393
                    if (!empty($primaryModel[$primaryName])) {
394
                        $this->populateInverseRelationToModels($primaryModel[$primaryName], $primaryModels, $name);
395 4
                    }
396 4
                }
397 4
            } else {
398
                foreach ($primaryModels as &$primaryModel) {
399
                    if (!empty($primaryModel[$primaryName])) {
400
                        $models = [$primaryModel[$primaryName]];
401 8
                        $this->populateInverseRelationToModels($models, $primaryModels, $name);
402 8
                        $primaryModel[$primaryName] = $models[0];
403 8
                    }
404 8
                }
405 8
            }
406
        }
407 4
    }
408
409
    private function populateInverseRelationToModels(array &$models, array $primaryModels, string $name): void
410
    {
411
        $model = reset($models);
412
        $isArray = is_array($model);
413
414
        /** @var ActiveQuery $relation */
415
        $relation = $isArray ? $this->getARInstance()->relationQuery($name) : $model->relationQuery($name);
416
        $buckets = $relation->buildBuckets($primaryModels);
417
        $link = $relation->getLink();
418
        $default = $relation->getMultiple() ? [] : null;
419
420 12
        if ($isArray) {
421
            /** @var array $model */
422 127
            foreach ($models as &$model) {
423
                $key = $this->getModelKey($model, $link);
424
                $model[$name] = $buckets[$key] ?? $default;
425
            }
426
        } else {
427
            /** @var ActiveRecordInterface $model */
428
            foreach ($models as $model) {
429 127
                $key = $this->getModelKey($model, $link);
430 72
                $model->populateRelation($name, $buckets[$key] ?? $default);
431 72
            }
432 72
        }
433 72
    }
434
435 72
    private function buildBuckets(
436 71
        array $models,
437 71
        array $viaModels = null,
438 71
        self $viaQuery = null
439
    ): array {
440
        if ($viaModels !== null) {
441 72
            $map = [];
442
            $linkValues = $this->link;
443 72
            $viaLink = $viaQuery->link ?? [];
444 72
            $viaLinkKeys = array_keys($viaLink);
445 5
            $viaVia = null;
446 5
447
            foreach ($viaModels as $viaModel) {
448 5
                $key1 = $this->getModelKey($viaModel, $viaLinkKeys);
449
                $key2 = $this->getModelKey($viaModel, $linkValues);
450
                $map[$key2][$key1] = true;
451
            }
452 127
453 127
            if ($viaQuery !== null) {
454
                $viaQuery->viaMap = $map;
455 127
                $viaVia = $viaQuery->getVia();
456 72
            }
457 71
458 71
            while ($viaVia) {
459 71
                /**
460 71
                 * @var ActiveQuery $viaViaQuery
461
                 *
462
                 * @psalm-suppress RedundantCondition
463
                 */
464
                $viaViaQuery = is_array($viaVia) ? $viaVia[1] : $viaVia;
465 127
                $map = $this->mapVia($map, $viaViaQuery->viaMap);
0 ignored issues
show
Bug introduced by
The property viaMap is declared private in Yiisoft\ActiveRecord\ActiveQuery and cannot be accessed from this context.
Loading history...
466 127
467 127
                $viaVia = $viaViaQuery->getVia();
468
            }
469
        }
470
471 127
        $buckets = [];
472 56
        $linkKeys = array_keys($this->link);
473 56
474
        if (isset($map)) {
475
            foreach ($models as $model) {
476
                $key = $this->getModelKey($model, $linkKeys);
477 127
                if (isset($map[$key])) {
478
                    foreach (array_keys($map[$key]) as $key2) {
479
                        /** @psalm-suppress InvalidArrayOffset */
480 5
                        $buckets[$key2][] = $model;
481
                    }
482 5
                }
483
            }
484 5
        } else {
485 5
            foreach ($models as $model) {
486 5
                $key = $this->getModelKey($model, $linkKeys);
487
                $buckets[$key][] = $model;
488
            }
489
        }
490 5
491
        if (!$this->multiple) {
492
            foreach ($buckets as $i => $bucket) {
493
                $buckets[$i] = reset($bucket);
494
            }
495
        }
496
497
        return $buckets;
498
    }
499
500
    private function mapVia(array $map, array $viaMap): array
501
    {
502 17
        $resultMap = [];
503
504 17
        foreach ($map as $key => $linkKeys) {
505
            $resultMap[$key] = [];
506 17
            foreach (array_keys($linkKeys) as $linkKey) {
507 17
                /** @psalm-suppress InvalidArrayOffset */
508 17
                $resultMap[$key] += $viaMap[$linkKey];
509 17
            }
510 17
        }
511
512
        return $resultMap;
513
    }
514 17
515
    /**
516
     * Indexes buckets by a column name.
517
     *
518
     * @param Closure|string $indexBy the name of the column by which the query results should be indexed by. This can
519
     * also be a {@see Closure} that returns the index value based on the given models data.
520
     */
521
    private function indexBuckets(array $buckets, Closure|string $indexBy): array
522 236
    {
523
        foreach ($buckets as &$models) {
524 236
            $models = ArArrayHelper::index($models, $indexBy);
525 36
        }
526 12
527
        return $buckets;
528 32
    }
529 32
530 32
    /**
531
     * @param array $attributes the attributes to prefix.
532 32
     *
533
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
534
     */
535
    private function prefixKeyColumns(array $attributes): array
536 36
    {
537 36
        if (!empty($this->join) || !empty($this->joinWith)) {
538 36
            if (empty($this->from)) {
539
                $alias = $this->getARInstance()->getTableName();
540
            } else {
541
                foreach ($this->from as $alias => $table) {
542
                    if (!is_string($alias)) {
543 236
                        $alias = $table;
544
                    }
545
                    break;
546 236
                }
547
            }
548 236
549
            if (isset($alias)) {
550 236
                foreach ($attributes as $i => $attribute) {
551
                    $attributes[$i] = "$alias.$attribute";
552 236
                }
553 236
            }
554
        }
555 232
556 232
        return $attributes;
557 232
    }
558 228
559
    /**
560 228
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
561
     */
562
    protected function filterByModels(array $models): void
563 228
    {
564
        $attributes = array_keys($this->link);
565
        $attributes = $this->prefixKeyColumns($attributes);
566
567
        $model = reset($models);
568 232
        $values = [];
569 232
570
        if (count($attributes) === 1) {
571
            /** single key */
572
            $attribute = reset($this->link);
573
574
            if ($model instanceof ActiveRecordInterface) {
575 8
                foreach ($models as $model) {
576
                    $value = $model->getAttribute($attribute);
577 8
578 8
                    if ($value !== null) {
579
                        if (is_array($value)) {
580 8
                            $values = [...$values, ...$value];
581 8
                        } else {
582
                            $values[] = $value;
583
                        }
584 8
                    }
585
                }
586 8
            } else {
587
                foreach ($models as $model) {
588
                    if (isset($model[$attribute])) {
589
                        $value = $model[$attribute];
590
591
                        if (is_array($value)) {
592 236
                            $values = [...$values, ...$value];
593 232
                        } else {
594 232
                            $values[] = $value;
595 232
                        }
596 232
                    }
597 228
                }
598
            }
599 8
600
            if (!empty($values)) {
601
                $scalarValues = array_filter($values, 'is_scalar');
602
                $nonScalarValues = array_diff_key($values, $scalarValues);
603 232
604 232
                $scalarValues = array_unique($scalarValues);
605
                $values = [...$scalarValues, ...$nonScalarValues];
606
            }
607 236
        } else {
608 236
            $nulls = array_fill_keys($this->link, null);
609
610
            if ($model instanceof ActiveRecordInterface) {
611
                foreach ($models as $model) {
612
                    $value = $model->getAttributes($this->link);
613
614
                    if (!empty($value)) {
615
                        $values[] = array_combine($attributes, array_merge($nulls, $value));
616 127
                    }
617
                }
618 127
            } else {
619
                foreach ($models as $model) {
620 127
                    $value = array_intersect_key($model, $nulls);
621 127
622
                    if (!empty($value)) {
623
                        $values[] = array_combine($attributes, array_merge($nulls, $value));
624 127
                    }
625
                }
626
            }
627
        }
628 127
629
        if (empty($values)) {
630 127
            $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

630
            $this->/** @scrutinizer ignore-call */ 
631
                   emulateExecution();
Loading history...
631
            $this->andWhere('1=0');
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

631
            $this->/** @scrutinizer ignore-call */ 
632
                   andWhere('1=0');
Loading history...
632
            return;
633
        }
634
635
        $this->andWhere(['in', $attributes, $values]);
636
    }
637
638 127
    private function getModelKey(ActiveRecordInterface|array $activeRecord, array $attributes): false|int|string
639
    {
640 127
        $key = [];
641
642
        if (is_array($activeRecord)) {
0 ignored issues
show
introduced by
The condition is_array($activeRecord) is always true.
Loading history...
643
            foreach ($attributes as $attribute) {
644
                if (isset($activeRecord[$attribute])) {
645
                    $key[] = $this->normalizeModelKey($activeRecord[$attribute]);
646
                }
647
            }
648 127
        } else {
649
            foreach ($attributes as $attribute) {
650
                $value = $activeRecord->getAttribute($attribute);
651
652
                if ($value !== null) {
653
                    $key[] = $this->normalizeModelKey($value);
654
                }
655
            }
656 28
        }
657
658 28
        if (count($key) > 1) {
659
            return serialize($key);
660
        }
661
662 28
        $key = reset($key);
663
664
        return is_scalar($key) ? $key : serialize($key);
665 28
    }
666
667 28
    /**
668
     * @param int|string|Stringable|null $value raw key value.
669
     *
670
     * @return int|string|null normalized key value.
671
     */
672 28
    private function normalizeModelKey(int|string|Stringable|null $value): int|string|null
673
    {
674
        if ($value instanceof Stringable) {
675
            /**
676
             * ensure matching to special objects, which are convertible to string, for cross-DBMS relations,
677
             * for example: `|MongoId`
678
             */
679
            $value = (string) $value;
680
        }
681
682 39
        return $value;
683
    }
684 39
685
    /**
686
     * @param array $primaryModels either array of AR instances or arrays.
687
     *
688
     * @throws Exception
689
     * @throws Throwable
690
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
691
     */
692 63
    private function findJunctionRows(array $primaryModels): array
693
    {
694 63
        if (empty($primaryModels)) {
695
            return [];
696
        }
697
698
        $this->filterByModels($primaryModels);
699
700
        /* @var $primaryModel ActiveRecord */
701
        $primaryModel = reset($primaryModels);
702
703
        if (!$primaryModel instanceof ActiveRecordInterface) {
0 ignored issues
show
introduced by
$primaryModel is always a sub-type of Yiisoft\ActiveRecord\ActiveRecordInterface.
Loading history...
704
            /** when primaryModels are array of arrays (asArray case) */
705
            $primaryModel = $this->arClass;
0 ignored issues
show
Unused Code introduced by
The assignment to $primaryModel is dead and can be removed.
Loading history...
706 113
        }
707
708 113
        return $this->asArray()->all();
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

708
        return $this->/** @scrutinizer ignore-call */ asArray()->all();
Loading history...
709
    }
710
711
    public function getMultiple(): bool
712
    {
713
        return $this->multiple;
714
    }
715
716
    /**
717
     * @return ActiveRecordInterface|null the primary model of a relational query.
718
     *
719 117
     * This is used only in lazy loading with dynamic query options.
720
     */
721 117
    public function getPrimaryModel(): ActiveRecordInterface|null
722
    {
723
        return $this->primaryModel;
724 252
    }
725
726 252
    /**
727
     * @psalm-return string[]
728 252
     */
729
    public function getLink(): array
730
    {
731 252
        return $this->link;
732
    }
733 252
734
    public function getVia(): array|ActiveQueryInterface|null
735 252
    {
736
        return $this->via;
737
    }
738 252
739
    public function multiple(bool $value): self
740 252
    {
741
        $this->multiple = $value;
742 252
743
        return $this;
744
    }
745
746
    public function primaryModel(ActiveRecordInterface $value): self
747
    {
748
        $this->primaryModel = $value;
749
750
        return $this;
751
    }
752
753
    public function link(array $value): self
754
    {
755
        $this->link = $value;
756
757
        return $this;
758
    }
759
}
760