packages/sql-fixture/src/Schema/StaticSchemaResolver.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlFixture\Schema;
6
7/**
8 * Resolves schemas from an in-memory, case-insensitive registry.
9 */
10final class StaticSchemaResolver implements SchemaResolverInterface
11{
12    /**
13     * @var array<string, TableSchema> Lower-cased table name => schema
14     */
15    private array $schemas = [];
16
17    /**
18     * @param iterable<TableSchema> $schemas
19     */
20    public function __construct(iterable $schemas = [])
21    {
22        foreach ($schemas as $schema) {
23            $this->register($schema);
24        }
25    }
26
27    /**
28     * Registers the table schema under its normalized name.
29     */
30    public function register(TableSchema $schema): void
31    {
32        $this->schemas[(new TableIdentifier())->normalize($schema->tableName)] = $schema;
33    }
34
35    /**
36     * Returns the schema registered for the table, or reports that it is missing.
37     * @throws SchemaNotFoundException
38     */
39    public function resolve(string $tableName): TableSchema
40    {
41        $schema = $this->schemas[(new TableIdentifier())->normalize($tableName)] ?? null;
42        if ($schema === null) {
43            throw new SchemaNotFoundException($tableName, $this->tableNames());
44        }
45
46        return $schema;
47    }
48
49    /**
50     * Reports whether the named table is registered.
51     */
52    public function has(string $tableName): bool
53    {
54        return isset($this->schemas[(new TableIdentifier())->normalize($tableName)]);
55    }
56
57    /**
58     * @return list<string>
59     */
60    public function tableNames(): array
61    {
62        return array_keys($this->schemas);
63    }
64
65}
66