Passed
Pull Request — master (#318)
by Sergei
02:53
created

ActiveRelationTrait::relatedRecords()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

184
        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

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

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

277
        /** @scrutinizer ignore-call */ 
278
        $indexBy = $this->getIndexBy();
Loading history...
278
        $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

278
        $this->/** @scrutinizer ignore-call */ 
279
               indexBy(null);
Loading history...
279
        $models = $this->all();
280 139
281 28
        if (isset($viaModels, $viaQuery)) {
282 28
            $buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery);
283
        } else {
284 28
            $buckets = $this->buildBuckets($models, $this->link);
285 28
        }
286
287 4
        $this->indexBy($indexBy);
288
289
        $indexBy = $this->getIndexBy();
290 28
291 8
        if ($indexBy !== null && $this->multiple) {
292
            $buckets = $this->indexBuckets($buckets, $indexBy);
293
        }
294 28
295
        $link = array_values($this->link);
296
        if (isset($viaQuery)) {
297
            $deepViaQuery = $viaQuery;
298
299
            while ($deepViaQuery->via) {
300
                $deepViaQuery = is_array($deepViaQuery->via) ? $deepViaQuery->via[1] : $deepViaQuery->via;
301
            }
302 123
303 123
            $link = array_values($deepViaQuery->link);
304 123
        }
305
306 123
        foreach ($primaryModels as $i => $primaryModel) {
307 72
            $keys = null;
308
            if ($this->multiple && count($link) === 1) {
309 123
                $primaryModelKey = reset($link);
310
                $keys = $primaryModel[$primaryModelKey] ?? null;
311
            }
312 123
            if (is_array($keys)) {
313
                $value = [];
314 123
                foreach ($keys as $key) {
315 17
                    $key = $this->normalizeModelKey($key);
316
                    if (isset($buckets[$key])) {
317
                        if ($indexBy !== null) {
318 123
                            /** if indexBy is set, array_merge will cause renumbering of numeric array */
319 123
                            foreach ($buckets[$key] as $bucketKey => $bucketValue) {
320 72
                                $value[$bucketKey] = $bucketValue;
321
                            }
322 72
                        } else {
323 5
                            $value = array_merge($value, $buckets[$key]);
324
                        }
325
                    }
326 72
                }
327
            } else {
328
                $key = $this->getModelKey($primaryModel, $link);
329 123
                $value = $buckets[$key] ?? ($this->multiple ? [] : null);
330 123
            }
331
332
            if ($primaryModel instanceof ActiveRecordInterface) {
333
                $primaryModel->populateRelation($name, $value);
334
            } else {
335
                $primaryModels[$i][$name] = $value;
336
            }
337
        }
338
        if ($this->inverseOf !== null) {
339
            $this->populateInverseRelation($primaryModels, $models, $name, $this->inverseOf);
340
        }
341
342
        return $models;
343
    }
344
345
    /**
346 123
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
347 123
     */
348
    private function populateInverseRelation(
349
        array &$primaryModels,
350 123
        array $models,
351 123
        string $primaryName,
352
        string $name
353 9
    ): void {
354
        if (empty($models) || empty($primaryModels)) {
355
            return;
356 123
        }
357 8
358
        $model = reset($models);
359
360 123
        if ($model instanceof ActiveRecordInterface) {
361
            /** @var ActiveQuery $relation */
362
            $relation = $model->getRelation($name);
363 12
        } else {
364
            /** @var ActiveQuery $relation */
365
            $relation = $this->getARInstance()->getRelation($name);
366
        }
367
368
        if ($relation->getMultiple()) {
369 12
            $buckets = $this->buildBuckets($primaryModels, $relation->getLink(), null, null, false);
370
            if ($model instanceof ActiveRecordInterface) {
371
                foreach ($models as $model) {
372 12
                    $key = $this->getModelKey($model, $relation->getLink());
373
                    if ($model instanceof ActiveRecordInterface) {
374
                        $model->populateRelation($name, $buckets[$key] ?? []);
375 12
                    }
376 12
                }
377
            } else {
378 4
                foreach ($primaryModels as $i => $primaryModel) {
379
                    if ($this->multiple) {
380
                        foreach ($primaryModel as $j => $m) {
381 12
                            $key = $this->getModelKey($m, $relation->getLink());
382 8
                            $primaryModels[$i][$j][$name] = $buckets[$key] ?? [];
383 8
                        }
384 8
                    } elseif (!empty($primaryModel[$primaryName])) {
385 8
                        $key = $this->getModelKey($primaryModel[$primaryName], $relation->getLink());
386 8
                        $primaryModels[$i][$primaryName][$name] = $buckets[$key] ?? [];
387
                    }
388
                }
389 8
            }
390 4
        } elseif ($this->multiple) {
391
            foreach ($primaryModels as $i => $primaryModel) {
392
                foreach ($primaryModel[$primaryName] as $j => $m) {
393
                    if ($m instanceof ActiveRecordInterface) {
394
                        $m->populateRelation($name, $primaryModel);
395 4
                    } else {
396 4
                        $primaryModels[$i][$primaryName][$j][$name] = $primaryModel;
397 4
                    }
398
                }
399
            }
400
        } else {
401 8
            foreach ($primaryModels as $i => $primaryModel) {
402 8
                if ($primaryModel[$primaryName] instanceof ActiveRecordInterface) {
403 8
                    $primaryModel[$primaryName]->populateRelation($name, $primaryModel);
404 8
                } elseif (!empty($primaryModel[$primaryName])) {
405 8
                    $primaryModels[$i][$primaryName][$name] = $primaryModel;
406
                }
407 4
            }
408
        }
409
    }
410
411
    private function buildBuckets(
412
        array $models,
413
        array $link,
414
        array $viaModels = null,
415
        self $viaQuery = null,
416
        bool $checkMultiple = true
417
    ): array {
418
        if ($viaModels !== null) {
419
            $map = [];
420 12
            $linkValues = array_values($link);
421
            $viaLink = $viaQuery->link ?? [];
422 127
            $viaLinkKeys = array_keys($viaLink);
423
            $viaVia = null;
424
425
            foreach ($viaModels as $viaModel) {
426
                $key1 = $this->getModelKey($viaModel, $viaLinkKeys);
427
                $key2 = $this->getModelKey($viaModel, $linkValues);
428
                $map[$key2][$key1] = true;
429 127
            }
430 72
431 72
            if ($viaQuery !== null) {
432 72
                $viaQuery->viaMap = $map;
433 72
                $viaVia = $viaQuery->getVia();
434
            }
435 72
436 71
            while ($viaVia) {
437 71
                /**
438 71
                 * @var ActiveQuery $viaViaQuery
439
                 *
440
                 * @psalm-suppress RedundantCondition
441 72
                 */
442
                $viaViaQuery = is_array($viaVia) ? $viaVia[1] : $viaVia;
443 72
                $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...
444 72
445 5
                $viaVia = $viaViaQuery->getVia();
446 5
            }
447
        }
448 5
449
        $buckets = [];
450
        $linkKeys = array_keys($link);
451
452 127
        if (isset($map)) {
453 127
            foreach ($models as $model) {
454
                $key = $this->getModelKey($model, $linkKeys);
455 127
                if (isset($map[$key])) {
456 72
                    foreach (array_keys($map[$key]) as $key2) {
457 71
                        /** @psalm-suppress InvalidArrayOffset */
458 71
                        $buckets[$key2][] = $model;
459 71
                    }
460 71
                }
461
            }
462
        } else {
463
            foreach ($models as $model) {
464
                $key = $this->getModelKey($model, $linkKeys);
465 127
                $buckets[$key][] = $model;
466 127
            }
467 127
        }
468
469
        if ($checkMultiple && !$this->multiple) {
470
            foreach ($buckets as $i => $bucket) {
471 127
                $buckets[$i] = reset($bucket);
472 56
            }
473 56
        }
474
475
        return $buckets;
476
    }
477 127
478
    private function mapVia(array $map, array $viaMap): array
479
    {
480 5
        $resultMap = [];
481
482 5
        foreach ($map as $key => $linkKeys) {
483
            $resultMap[$key] = [];
484 5
            foreach (array_keys($linkKeys) as $linkKey) {
485 5
                /** @psalm-suppress InvalidArrayOffset */
486 5
                $resultMap[$key] += $viaMap[$linkKey];
487
            }
488
        }
489
490 5
        return $resultMap;
491
    }
492
493
    /**
494
     * Indexes buckets by column name.
495
     *
496
     * @param callable|string $indexBy the name of the column by which the query results should be indexed by. This can
497
     * also be a callable(e.g. anonymous function) that returns the index value based on the given row data.
498
     */
499
    private function indexBuckets(array $buckets, callable|string $indexBy): array
500
    {
501
        $result = [];
502 17
503
        foreach ($buckets as $key => $models) {
504 17
            $result[$key] = [];
505
            foreach ($models as $model) {
506 17
                $index = is_string($indexBy) ? $model[$indexBy] : $indexBy($model);
507 17
                $result[$key][$index] = $model;
508 17
            }
509 17
        }
510 17
511
        return $result;
512
    }
513
514 17
    /**
515
     * @param array $attributes the attributes to prefix.
516
     *
517
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
518
     */
519
    private function prefixKeyColumns(array $attributes): array
520
    {
521
        if (!empty($this->join) || !empty($this->joinWith)) {
522 236
            if (empty($this->from)) {
523
                $alias = $this->getARInstance()->getTableName();
524 236
            } else {
525 36
                foreach ($this->from as $alias => $table) {
526 12
                    if (!is_string($alias)) {
527
                        $alias = $table;
528 32
                    }
529 32
                    break;
530 32
                }
531
            }
532 32
533
            if (isset($alias)) {
534
                foreach ($attributes as $i => $attribute) {
535
                    $attributes[$i] = "$alias.$attribute";
536 36
                }
537 36
            }
538 36
        }
539
540
        return $attributes;
541
    }
542
543 236
    /**
544
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
545
     */
546 236
    protected function filterByModels(array $models): void
547
    {
548 236
        $attributes = array_keys($this->link);
549
550 236
        $attributes = $this->prefixKeyColumns($attributes);
551
552 236
        $values = [];
553 236
        if (count($attributes) === 1) {
554
            /** single key */
555 232
            $attribute = reset($this->link);
556 232
            foreach ($models as $model) {
557 232
                $value = isset($model[$attribute]) || (is_object($model) && property_exists($model, $attribute)) ? $model[$attribute] : null;
558 228
                if ($value !== null) {
559
                    if (is_array($value)) {
560 228
                        $values = array_merge($values, $value);
561
                    } elseif ($value instanceof ArrayExpression && $value->getDimension() === 1) {
562
                        $values = array_merge($values, $value->getValue());
563 228
                    } else {
564
                        $values[] = $value;
565
                    }
566
                }
567
            }
568 232
569 232
            if (empty($values)) {
570
                $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

570
                $this->/** @scrutinizer ignore-call */ 
571
                       emulateExecution();
Loading history...
571
            }
572
        } else {
573
            /**
574
             * composite keys ensure keys of $this->link are prefixed the same way as $attributes.
575 8
             */
576
            $prefixedLink = array_combine($attributes, $this->link);
577 8
578 8
            foreach ($models as $model) {
579
                $v = [];
580 8
581 8
                foreach ($prefixedLink as $attribute => $link) {
582
                    $v[$attribute] = $model[$link];
583
                }
584 8
585
                $values[] = $v;
586 8
587
                if (empty($v)) {
588
                    $this->emulateExecution();
589
                }
590
            }
591
        }
592 236
593 232
        if (!empty($values)) {
594 232
            $scalarValues = [];
595 232
            $nonScalarValues = [];
596 232
            foreach ($values as $value) {
597 228
                if (is_scalar($value)) {
598
                    $scalarValues[] = $value;
599 8
                } else {
600
                    $nonScalarValues[] = $value;
601
                }
602
            }
603 232
604 232
            $scalarValues = array_unique($scalarValues);
605
            $values = [...$scalarValues, ...$nonScalarValues];
606
        }
607 236
608 236
        $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

608
        $this->/** @scrutinizer ignore-call */ 
609
               andWhere(['in', $attributes, $values]);
Loading history...
609
    }
610
611
    private function getModelKey(ActiveRecordInterface|array $activeRecord, array $attributes): false|int|string
612
    {
613
        $key = [];
614
615
        foreach ($attributes as $attribute) {
616 127
            if (isset($activeRecord[$attribute]) || (is_object($activeRecord) && property_exists($activeRecord, $attribute))) {
617
                $key[] = $this->normalizeModelKey($activeRecord[$attribute]);
618 127
            }
619
        }
620 127
621 127
        if (count($key) > 1) {
622
            return serialize($key);
623
        }
624 127
625
        $key = reset($key);
626
627
        return is_scalar($key) ? $key : serialize($key);
628 127
    }
629
630 127
    /**
631
     * @return int|string|null normalized key value.
632
     */
633
    private function normalizeModelKey(mixed $value): int|string|null
634
    {
635
        if ($value instanceof Stringable) {
636
            /**
637
             * ensure matching to special objects, which are convertible to string, for cross-DBMS relations,
638 127
             * for example: `|MongoId`
639
             */
640 127
            $value = (string) $value;
641
        }
642
643
        return $value;
644
    }
645
646
    /**
647
     * @param array $primaryModels either array of AR instances or arrays.
648 127
     *
649
     * @throws Exception
650
     * @throws Throwable
651
     * @throws \Yiisoft\Definitions\Exception\InvalidConfigException
652
     */
653
    private function findJunctionRows(array $primaryModels): array
654
    {
655
        if (empty($primaryModels)) {
656 28
            return [];
657
        }
658 28
659
        $this->filterByModels($primaryModels);
660
661
        /* @var $primaryModel ActiveRecord */
662 28
        $primaryModel = reset($primaryModels);
663
664
        if (!$primaryModel instanceof ActiveRecordInterface) {
0 ignored issues
show
introduced by
$primaryModel is always a sub-type of Yiisoft\ActiveRecord\ActiveRecordInterface.
Loading history...
665 28
            /** when primaryModels are array of arrays (asArray case) */
666
            $primaryModel = $this->arClass;
0 ignored issues
show
Unused Code introduced by
The assignment to $primaryModel is dead and can be removed.
Loading history...
667 28
        }
668
669
        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

669
        return $this->/** @scrutinizer ignore-call */ asArray()->all();
Loading history...
670
    }
671
672 28
    public function getMultiple(): bool
673
    {
674
        return $this->multiple;
675
    }
676
677
    /**
678
     * @return ActiveRecordInterface|null the primary model of a relational query.
679
     *
680
     * This is used only in lazy loading with dynamic query options.
681
     */
682 39
    public function getPrimaryModel(): ActiveRecordInterface|null
683
    {
684 39
        return $this->primaryModel;
685
    }
686
687
    /**
688
     * @psalm-return string[]
689
     */
690
    public function getLink(): array
691
    {
692 63
        return $this->link;
693
    }
694 63
695
    public function getVia(): array|ActiveQueryInterface|null
696
    {
697
        return $this->via;
698
    }
699
700
    public function multiple(bool $value): self
701
    {
702
        $this->multiple = $value;
703
704
        return $this;
705
    }
706 113
707
    public function primaryModel(ActiveRecordInterface $value): self
708 113
    {
709
        $this->primaryModel = $value;
710
711
        return $this;
712
    }
713
714
    public function link(array $value): self
715
    {
716
        $this->link = $value;
717
718
        return $this;
719 117
    }
720
}
721