Lines 95.18% 158 / 166
Methods 90.47% 38 / 42
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 addConstraints 100.00% 4 / 4 100.00% 1 / 1 3
 executeResults 100.00% 2 / 2 100.00% 1 / 1 2
 applyEagerOrdering 100.00% 4 / 4 100.00% 1 / 1 3
 match 100.00% 8 / 8 100.00% 1 / 1 4
 [BlueprintAU\Radiant\Relations\MorphOneOrMany] __construct 100.00% 2 / 2 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\MorphOneOrMany] getTypeColumn 0.00% 0 / 1 0.00% 0 / 1 2
 [BlueprintAU\Radiant\Relations\MorphOneOrMany] parentMorphAlias 100.00% 1 / 1 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] defersConstraints 100.00% 1 / 1 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] withName 100.00% 5 / 5 100.00% 1 / 1 2
 [BlueprintAU\Radiant\Relations\Relation] markComposed 100.00% 3 / 3 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] servesCache 100.00% 1 / 1 100.00% 1 / 1 3
 [BlueprintAU\Radiant\Relations\Relation] eagerCache 66.66% 2 / 3 0.00% 0 / 1 2.15
 [BlueprintAU\Radiant\Relations\Relation] compositionQuery 100.00% 6 / 6 100.00% 1 / 1 2
 [BlueprintAU\Radiant\Relations\Relation] readQuery 100.00% 1 / 1 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] relatedClass 100.00% 1 / 1 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] eagerLoad 81.81% 9 / 11 0.00% 0 / 1 4.10
 [BlueprintAU\Radiant\Relations\Relation] eagerLoadChunk 84.61% 22 / 26 0.00% 0 / 1 4.06
 [BlueprintAU\Radiant\Relations\Relation] get 100.00% 3 / 3 100.00% 1 / 1 3
 [BlueprintAU\Radiant\Relations\Relation] wrapCached 100.00% 3 / 3 100.00% 1 / 1 2
 [BlueprintAU\Radiant\Relations\Relation] getQuery 100.00% 1 / 1 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] where 100.00% 4 / 4 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] whereNested 100.00% 4 / 4 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] whereExists 100.00% 4 / 4 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] whereInQuery 100.00% 4 / 4 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] orderBy 100.00% 4 / 4 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] limit 100.00% 4 / 4 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] offset 100.00% 4 / 4 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] select 100.00% 4 / 4 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] groupBy 100.00% 4 / 4 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] having 100.00% 4 / 4 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] getRelated 100.00% 1 / 1 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] relatedClasses 100.00% 1 / 1 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] getForeignKey 100.00% 5 / 5 100.00% 1 / 1 2
 [BlueprintAU\Radiant\Relations\Relation] getLocalKey 100.00% 5 / 5 100.00% 1 / 1 2
 [BlueprintAU\Radiant\Relations\Relation] getForeignKeys 100.00% 5 / 5 100.00% 1 / 1 2
 [BlueprintAU\Radiant\Relations\Relation] getLocalKeys 100.00% 5 / 5 100.00% 1 / 1 2
 [BlueprintAU\Radiant\Relations\Relation] isComposite 100.00% 1 / 1 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] eagerKeyColumn 100.00% 1 / 1 100.00% 1 / 1 1
 [BlueprintAU\Radiant\Relations\Relation] applyKeyTuple 100.00% 4 / 4 100.00% 1 / 1 3
 [BlueprintAU\Radiant\Relations\Relation] parentKeyValues 100.00% 4 / 4 100.00% 1 / 1 2
 [BlueprintAU\Radiant\Relations\Relation] tupleValues 100.00% 4 / 4 100.00% 1 / 1 2
 [BlueprintAU\Radiant\Relations\Relation] serializeKey 100.00% 3 / 3 100.00% 1 / 1 2
23final class MorphOne extends MorphOneOrMany
24{
25    /**
26     * Order the lazy query stably by the related PK â€” first-wins must be
27     * deterministic.
28     *
29     * @return void
30     */
31    #[\Override]
32    protected function addConstraints(): void
33    {
34        $primaryKeys = MetadataFactory::for($this->getRelated())->primaryKeys;
35
36        if (count($primaryKeys) === 1 && $primaryKeys[0]->name !== null) {
37            $this->query = $this->query->orderBy($primaryKeys[0]->name);
38        }
39
40        parent::addConstraints();
41    }
42
43    /**
44     * Run the constrained query and keep only the first match.
45     *
46     * @return Collection<int, TRelated>
47     */
48    #[\Override]
49    protected function executeResults(): Collection
50    {
51        $first = $this->query->first();
52
53        return Collection::make($first === null ? [] : [$first]);
54    }
55
56    /**
57     * Order the eager-load query stably, mirroring the lazy path.
58     *
59     * @param  ModelQueryBuilder<TRelated>  $query
60     * @return ModelQueryBuilder<TRelated>
61     */
62    #[\Override]
63    protected function applyEagerOrdering(ModelQueryBuilder $query): ModelQueryBuilder
64    {
65        $primaryKeys = MetadataFactory::for($this->getRelated())->primaryKeys;
66
67        if (count($primaryKeys) === 1 && $primaryKeys[0]->name !== null) {
68            $query = $query->orderBy($primaryKeys[0]->name);
69        }
70
71        return parent::applyEagerOrdering($query);
72    }
73
74    /**
75     * Distribute eager results onto parents â€” first match per FK value.
76     *
77     * @param  list<Model>  $parents
78     * @param  Collection<int, TRelated>  $results
79     * @param  string  $name
80     * @param  list<int|string|null|list<int|string|null>>|null  $eagerParentKeys  Unused.
81     * @return void
82     */
83    #[\Override]
84    public function match(array $parents, Collection $results, string $name, ?array $eagerParentKeys = null): void
85    {
86        $first = [];
87
88        foreach ($results as $related) {
89            $key = self::serializeKey($related->attribute($this->getForeignKey()));
90
91            if (!isset($first[$key])) {
92                $first[$key] = $related;
93            }
94        }
95
96        foreach ($parents as $parent) {
97            $key = self::serializeKey($parent->attribute($this->getLocalKey()));
98            $parent->setRelation($name, $first[$key] ?? null);
99        }
100    }
101}

Inherited from BlueprintAU\Radiant\Relations\MorphOneOrMany

42    public function __construct(
43        Model $parent,
44        string $related,
45        string $foreignKey,
46        string $localKey,
47        string $typeColumn,
48    ) {
49        $this->typeColumn = $typeColumn;
50
51        parent::__construct($parent, $related, $foreignKey, $localKey);
52    }
59    final public function getTypeColumn(): string
60    {
61        return $this->typeColumn;
62    }
70    final protected function parentMorphAlias(): string
71    {
72        return $this->parent::class;
73    }

Inherited from BlueprintAU\Radiant\Relations\Relation

123    protected function defersConstraints(): bool
124    {
125        return false;
126    }
137    final public function withName(?string $name): static
138    {
139        if ($name === null) {
140            return $this;
141        }
142
143        $clone = clone $this;
144        $clone->name = $name;
145
146        return $clone;
147    }
158    protected function markComposed(): static
159    {
160        $clone = clone $this;
161        $clone->composed = true;
162
163        return $clone;
164    }
171    final protected function servesCache(): bool
172    {
173        return $this->name !== null && !$this->composed && $this->parent->relationLoaded($this->name);
174    }
181    protected function eagerCache(): Collection
182    {
183        if ($this->name === null) {
184            return Collection::make([]);
185        }
186
187        return $this->wrapCached($this->parent->cachedRelation($this->name));
188    }
195    protected function compositionQuery(): ModelQueryBuilder
196    {
197        if (!isset($this->query)) {
198            throw new \LogicException(
199                static::class . ' cannot compose filters â€” its query is built lazily per '
200                . 'resolved type; read the results with get() instead.'
201            );
202        }
203
204        return $this->query;
205    }
212    protected function readQuery(): ModelQueryBuilder
213    {
214        return $this->getQuery();
215    }
222    protected function relatedClass(): string
223    {
224        return $this->related;
225    }
258    public function eagerLoad(array $parentKeys): EagerResult
259    {
260        if ($parentKeys === []) {
261            return EagerResult::fromModels([]);
262        }
263
264        $models = [];
265        $parentKeysOut = null;
266
267        foreach (array_chunk($parentKeys, self::EAGER_KEY_CHUNK) as $chunk) {
268            $chunkResult = $this->eagerLoadChunk($chunk);
269            array_push($models, ...$chunkResult->models->all());
270
271            if ($chunkResult->parentKeys !== null) {
272                $parentKeysOut ??= [];
273                array_push($parentKeysOut, ...$chunkResult->parentKeys);
274            }
275        }
276
277        return new EagerResult(EagerResult::listToCollection($models), $parentKeysOut);
278    }
286    protected function eagerLoadChunk(array $parentKeys): EagerResult
287    {
288        $query = $this->related::newQuery();
289
290        $query = $this->applyEagerOrdering($query);
291
292        if ($this->isComposite()) {
293            $foreignKeys = $this->getForeignKeys();
294            $localKeys = $this->getLocalKeys();
295
296            // The OR-of-groups lands INSIDE one outer AND-group: the key
297            // set is ONE constraint unit. The related builder auto-applies
298            // trait scopes (e.g. soft-delete `deleted_at IS NULL`) as
299            // leading AND-groups â€” flat top-level ORs would compile to
300            // `(scope) OR (fk = ? AND ...) OR ...` and let a scope-excluded
301            // row back in whenever its key matched. Grouped, the scope
302            // ANDs against the whole set.
303            return EagerResult::fromCollection($query->whereNested(
304                function (WhereBuilder $nested) use ($foreignKeys, $localKeys, $parentKeys): WhereBuilder {
305                    $grouped = $nested;
306
307                    foreach ($parentKeys as $parentKey) {
308                        if (!is_array($parentKey)) {
309                            throw new \InvalidArgumentException(
310                                'A composite relation key requires column => value key maps for eager loading; '
311                                    . 'got ' . get_debug_type($parentKey) . '.'
312                            );
313                        }
314
315                        $grouped = $grouped->orWhereNested(
316                            fn (WhereBuilder $keyGroup): WhereBuilder => self::applyKeyTuple(
317                                $keyGroup,
318                                $foreignKeys,
319                                $localKeys,
320                                $parentKey,
321                            )
322                        );
323                    }
324
325                    return $grouped;
326                }
327            )->get());
328        }
329
330        return EagerResult::fromCollection($query->whereIn($this->getForeignKey(), $parentKeys)->get());
331    }
363    final public function get(bool $fresh = false): Collection
364    {
365        if (!$fresh && $this->servesCache()) {
366            return $this->eagerCache();
367        }
368
369        return $this->executeResults();
370    }
378    private function wrapCached(Model|Collection|null $value): Collection
379    {
380        if ($value instanceof Model) {
381            /** @var Collection<int, TRelated> */
382            return Collection::make([$value]);
383        }
384
385        /** @var Collection<int, TRelated> */
386        return $value ?? Collection::make([]);
387    }
404    final public function getQuery(): ModelQueryBuilder
405    {
406        return $this->query;
407    }
418    final public function where(
419        string|Expression $column,
420        WhereOperator|string $operator,
421        mixed $value,
422        WhereBoolean $boolean = WhereBoolean::And,
423    ): static {
424        $clone = clone $this;
425        $clone->composed = true;
426        $clone->query = $this->compositionQuery()->where($column, $operator, $value, $boolean);
427
428        return $clone;
429    }
440    final public function whereNested(
441        callable $callback,
442        WhereBoolean $boolean = WhereBoolean::And,
443    ): static {
444        $clone = clone $this;
445        $clone->composed = true;
446        $clone->query = $this->compositionQuery()->whereNested($callback, $boolean);
447
448        return $clone;
449    }
459    final public function whereExists(
460        \BlueprintAU\Radiant\Database\Query\QueryBuilder $query,
461        WhereBoolean $boolean = WhereBoolean::And,
462        bool $negated = false,
463    ): static {
464        $clone = clone $this;
465        $clone->composed = true;
466        $clone->query = $this->compositionQuery()->whereExists($query, $boolean, $negated);
467
468        return $clone;
469    }
480    final public function whereInQuery(
481        string $column,
482        \BlueprintAU\Radiant\Database\Query\QueryBuilder $query,
483        WhereBoolean $boolean = WhereBoolean::And,
484        bool $negated = false,
485    ): static {
486        $clone = clone $this;
487        $clone->composed = true;
488        $clone->query = $this->compositionQuery()->whereInQuery($column, $query, $boolean, $negated);
489
490        return $clone;
491    }
500    final public function orderBy(string|Expression $column, SortDirection|string $direction = SortDirection::Asc): static
501    {
502        $clone = clone $this;
503        $clone->composed = true;
504        $clone->query = $this->compositionQuery()->orderBy($column, $direction);
505
506        return $clone;
507    }
515    final public function limit(int $limit): static
516    {
517        $clone = clone $this;
518        $clone->composed = true;
519        $clone->query = $this->compositionQuery()->limit($limit);
520
521        return $clone;
522    }
530    final public function offset(int $offset): static
531    {
532        $clone = clone $this;
533        $clone->composed = true;
534        $clone->query = $this->compositionQuery()->offset($offset);
535
536        return $clone;
537    }
545    final public function select(string|Expression|Aggregate ...$columns): static
546    {
547        // No args â†’ the default `['*']` select.
548        $clone = clone $this;
549        $clone->composed = true;
550        $clone->query = $this->compositionQuery()->select(...$columns);
551
552        return $clone;
553    }
561    final public function groupBy(string|array $columns): static
562    {
563        $clone = clone $this;
564        $clone->composed = true;
565        $clone->query = $this->compositionQuery()->groupBy($columns);
566
567        return $clone;
568    }
578    final public function having(string|Expression|Aggregate $column, WhereOperator|string $operator, mixed $value): static
579    {
580        $clone = clone $this;
581        $clone->composed = true;
582        $clone->query = $this->compositionQuery()->having($column, $operator, $value);
583
584        return $clone;
585    }
592    final public function getRelated(): string
593    {
594        return $this->related;
595    }
605    public function relatedClasses(): array
606    {
607        return [$this->related];
608    }
616    final public function getForeignKey(): string
617    {
618        return is_string($this->foreignKey)
619            ? $this->foreignKey
620            : throw new \LogicException(
621                'This relation uses a composite foreign key; call getForeignKeys() instead.'
622            );
623    }
631    final public function getLocalKey(): string
632    {
633        return is_string($this->localKey)
634            ? $this->localKey
635            : throw new \LogicException(
636                'This relation uses a composite local key; call getLocalKeys() instead.'
637            );
638    }
646    final public function getForeignKeys(): array
647    {
648        return is_array($this->foreignKey)
649            ? $this->foreignKey
650            : throw new \LogicException(
651                'This relation uses a single foreign key; call getForeignKey() instead.'
652            );
653    }
661    final public function getLocalKeys(): array
662    {
663        return is_array($this->localKey)
664            ? $this->localKey
665            : throw new \LogicException(
666                'This relation uses a single local key; call getLocalKey() instead.'
667            );
668    }
675    final public function isComposite(): bool
676    {
677        return is_array($this->foreignKey);
678    }
685    public function eagerKeyColumn(): string|array
686    {
687        return $this->localKey;
688    }
702    final protected static function applyKeyTuple(
703        WhereBuilder $query,
704        array $foreignKeys,
705        array $localKeys,
706        array $values,
707    ): WhereBuilder {
708        foreach ($foreignKeys as $i => $foreignKey) {
709            $value = $values[$localKeys[$i]] ?? null;
710            $query = $query->where($foreignKey, $value === null ? WhereOperator::Null : WhereOperator::Eq, $value);
711        }
712
713        return $query;
714    }
722    final protected function parentKeyValues(array $localKeys): array
723    {
724        $values = [];
725
726        foreach ($localKeys as $localKey) {
727            $values[$localKey] = $this->parent->attribute($localKey);
728        }
729
730        return $values;
731    }
744    final protected static function tupleValues(Model $model, array $columns): array
745    {
746        $values = [];
747
748        foreach ($columns as $column) {
749            $values[] = $model->attribute($column);
750        }
751
752        return $values;
753    }
766    final protected static function serializeKey(int|string|null|array $key): string
767    {
768        if (!is_array($key)) {
769            return (string) $key;
770        }
771
772        return json_encode($key, JSON_THROW_ON_ERROR);
773    }