Lines 96.44% 190 / 197
Methods 92.50% 37 / 40
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 addConstraints 100.00% 16 / 16 100.00% 1 / 1 5
 executeResults 100.00% 2 / 2 100.00% 1 / 1 2
 applyEagerOrdering 100.00% 4 / 4 100.00% 1 / 1 3
 match 100.00% 13 / 13 100.00% 1 / 1 6
 [BlueprintAU\Radiant\Relations\Relation] __construct 100.00% 18 / 18 100.00% 1 / 1 8
 [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
24final class HasOne extends HasMany
25{
26    /**
27     * Constrain the related query to the parent's key, stably ordered.
28     *
29     * @return void
30     */
31    protected function addConstraints(): void
32    {
33        $primaryKeys = MetadataFactory::for($this->related)->primaryKeys;
34
35        if (count($primaryKeys) === 1 && $primaryKeys[0]->name !== null) {
36            $this->query = $this->query->orderBy($primaryKeys[0]->name);
37        }
38
39        if ($this->isComposite()) {
40            // The tuple lands inside a whereNested GROUP â€” the relation
41            // constraint is ONE unit: the parts AND within the parens, and
42            // a caller's later `->orWhere(...)` ORs at the constraint's
43            // edges instead of against the tuple's PARTS.
44            $this->query = $this->query->whereNested(fn (WhereBuilder $nested): WhereBuilder => self::applyKeyTuple(
45                $nested,
46                $this->getForeignKeys(),
47                $this->getLocalKeys(),
48                $this->parentKeyValues($this->getLocalKeys()),
49            ));
50
51            return;
52        }
53
54        $parentKey = $this->parent->attribute($this->getLocalKey());
55
56        if ($parentKey === null) {
57            // Null parent key â†’ no results, without compiling a meaningless
58            // query (BelongsTo's convention; `fk = NULL` matches no rows).
59            $this->query = $this->query->whereRaw('1 = 0', []);
60            return;
61        }
62
63        $this->query = $this->query->where($this->getForeignKey(), WhereOperator::Eq, $parentKey);
64    }
65
66    /**
67     * Run the constrained query and keep only the first match.
68     *
69     * @return Collection<int, TRelated>
70     */
71    #[\Override]
72    protected function executeResults(): Collection
73    {
74        $first = $this->query->first();
75
76        return Collection::make($first === null ? [] : [$first]);
77    }
78
79    /**
80     * Order the eager-load query stably, mirroring the lazy path.
81     *
82     * @param  ModelQueryBuilder<TRelated>  $query
83     * @return ModelQueryBuilder<TRelated>
84     */
85    protected function applyEagerOrdering(ModelQueryBuilder $query): ModelQueryBuilder
86    {
87        $primaryKeys = MetadataFactory::for($this->related)->primaryKeys;
88
89        if (count($primaryKeys) === 1 && $primaryKeys[0]->name !== null) {
90            $query = $query->orderBy($primaryKeys[0]->name);
91        }
92
93        return $query;
94    }
95
96    /**
97     * Distribute eager results onto parents â€” first match per FK value.
98     *
99     * @param  list<Model>  $parents
100     * @param  Collection<int, TRelated>  $results
101     * @param  string  $name
102     * @param  list<int|string|null|list<int|string|null>>|null  $eagerParentKeys  Unused.
103     * @return void
104     */
105    public function match(array $parents, Collection $results, string $name, ?array $eagerParentKeys = null): void
106    {
107        $first = [];
108
109        foreach ($results as $related) {
110            $key = $this->isComposite()
111                ? self::serializeKey(self::tupleValues($related, $this->getForeignKeys()))
112                : $related->attribute($this->getForeignKey());
113
114            if (!isset($first[self::serializeKey($key)])) {
115                $first[self::serializeKey($key)] = $related;
116            }
117        }
118
119        foreach ($parents as $parent) {
120            $key = $this->isComposite()
121                ? self::tupleValues($parent, $this->getLocalKeys())
122                : $parent->attribute($this->getLocalKey());
123            $related = $first[self::serializeKey($key)] ?? null;
124            $parent->setRelation($name, $related);
125        }
126    }
127}

Inherited from BlueprintAU\Radiant\Relations\Relation

81    public function __construct(
82        protected readonly Model $parent,
83        protected readonly string $related,
84        protected readonly string|array $foreignKey,
85        protected readonly string|array $localKey,
86    ) {
87        if (is_array($foreignKey) !== is_array($localKey)) {
88            throw new \InvalidArgumentException(
89                "A relation's foreign key and local key must be BOTH single columns or BOTH "
90                    . "composite column lists; got one of each on [{$related}]."
91            );
92        }
93
94        if ($foreignKey === [] || $localKey === []) {
95            throw new \InvalidArgumentException(
96                'A composite relation key requires at least one column; got an empty list.'
97            );
98        }
99
100        if (is_array($foreignKey) && is_array($localKey) && count($foreignKey) !== count($localKey)) {
101            throw new \InvalidArgumentException(
102                "A composite relation key's foreign and local columns must have matching "
103                    . 'arity; got ' . count($foreignKey) . ' and ' . count($localKey) . '.'
104            );
105        }
106
107        // MorphTo resolves its related model per row, so it has no query
108        // to build here â€” it handles that itself, lazily.
109        if ($this->defersConstraints()) {
110            return;
111        }
112
113        $this->query = $this->related::newQuery();
114        $this->addConstraints();
115    }
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    }