packages/sql-faker/src/Generation/Value/ChoiceDomain.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlFaker\Generation\Value;
6
7use Closure;
8use Override;
9
10/**
11 * Declares alternative constructive spelling domains, such as quoted and prefixed binary values.
12 */
13final class ChoiceDomain implements ValueDomain
14{
15    /**
16     * @var non-empty-list<ValueDomain>
17     */
18    private readonly array $domains;
19
20    /**
21     * Requires at least one complete domain rather than a finite sample of an unknown set.
22     */
23    public function __construct(ValueDomain $first, ValueDomain ...$others)
24    {
25        $this->domains = [$first, ...array_values($others)];
26    }
27
28    /**
29     * @param Closure(positive-int): int $choose
30     */
31    #[Override]
32    public function choose(Closure $choose): string
33    {
34        return $this->domains[$choose(count($this->domains))]->choose($choose);
35    }
36    /**
37     * @return list<int>
38     */
39    #[Override]
40    public function match(string $value, int $offset = 0): array
41    {
42        $ends = [];
43        foreach ($this->domains as $domain) {
44            $ends = [...$ends, ...$domain->match($value, $offset)];
45        }
46        return array_values(array_unique($ends));
47    }
48
49}
50