packages/sql-semantics-postgres/src/Model/Statement/Shape/Fields.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Model\Statement\Shape;
6
7use ArrayIterator;
8use Countable;
9use IteratorAggregate;
10use SqlSemantics\Platform\PostgreSql\Model\Diagnostic\Check;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Comparison;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Snapshot;
13
14/**
15 * The ordered, read-only output fields of a query whose shape is complete.
16 *
17 * Order and duplicate names are kept. The collection offers listing,
18 * iteration, counting, positional lookup and name lookup, and nothing that
19 * adds, removes, reorders or replaces a field.
20 *
21 * @visibility public
22 * @example Looking fields up by position and by name
23 *     $operation = (new \SqlSemantics\Platform\PostgreSql\Semantics())->analyze('SELECT 1 AS a, 2 AS a, 3 AS b');
24 *     $fields = $operation->fields();
25 *     [count($fields), $fields->at(2)->name?->value, $fields->lookup('a') instanceof \SqlSemantics\Platform\PostgreSql\Model\Statement\Shape\AmbiguousFields] // => [3, 'b', true]
26 * @implements IteratorAggregate<int, Field>
27 */
28final class Fields implements Countable, IteratorAggregate
29{
30    use Snapshot;
31
32    /**
33     * @var list<Field> The fields in output order
34     */
35    public readonly array $items;
36
37    /**
38     * @param list<Field> $items The fields in output order
39     * @param Comparison $names How output names are compared
40     */
41    public function __construct(array $items, public readonly Comparison $names)
42    {
43        $this->items = Check::listOf($items, Field::class, 'Fields are an ordered list of fields.');
44        foreach ($this->items as $position => $field) {
45            Check::input($field->position === $position, 'Each field holds its own output position.');
46        }
47    }
48
49    /**
50     * Counts the output positions.
51     */
52    public function count(): int
53    {
54        return count($this->items);
55    }
56
57    /**
58     * Iterates the fields in output order.
59     *
60     * @return ArrayIterator<int, Field>
61     */
62    public function getIterator(): ArrayIterator
63    {
64        return new ArrayIterator($this->items);
65    }
66
67    /**
68     * Answers the field at a zero-based output position.
69     */
70    public function at(int $position): Field
71    {
72        Check::input(isset($this->items[$position]), 'No field exists at the requested position.');
73
74        return $this->items[$position];
75    }
76
77    /**
78     * Finds the fields a name denotes, distinguishing one, none and several.
79     *
80     * When a field's name depends on missing inputs, no lookup is decided: the
81     * known matches are candidates of a dependent lookup.
82     */
83    public function lookup(string $name): UniqueField|AbsentField|AmbiguousFields|DependentField
84    {
85        $matches = [];
86        $missing = [];
87        foreach ($this->items as $field) {
88            if ($field->name !== null && $this->names->equal($field->name->value, $name)) {
89                $matches[] = $field;
90            }
91            array_push($missing, ...$field->slot->unnamed);
92        }
93        if ($missing !== []) {
94            return new DependentField($name, $matches, $missing);
95        }
96        if ($matches === []) {
97            return new AbsentField($name);
98        }
99
100        return count($matches) === 1 ? new UniqueField($matches[0]) : new AmbiguousFields($name, $matches);
101    }
102}
103