packages/sql-fixture/src/Provider/DdlDirectory.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlFixture\Provider;
6
7use RuntimeException;
8use SqlFixture\Schema\SchemaParserInterface;
9use SqlFixture\Schema\TableSchema;
10
11/**
12 * Loads table schemas from the SQL files in a directory.
13 *
14 * @visibility root
15 */
16final class DdlDirectory
17{
18 /**
19 * Load all SQL files from the DDL directory.
20 *
21 * @return array<string, TableSchema>
22 * @throws RuntimeException
23 */
24 public function loadSchemas(string $ddlPath, SchemaParserInterface $parser): array
25 {
26 if (!is_dir($ddlPath)) {
27 throw new RuntimeException("DDL path is not a directory: {$ddlPath}");
28 }
29
30 $files = glob($ddlPath . '/*.sql');
31 if ($files === false) {
32 throw new RuntimeException("Failed to read DDL directory: {$ddlPath}");
33 }
34
35 $schemas = [];
36 foreach ($files as $file) {
37 $schema = (new DdlFile())->loadSchemaFile($file, $parser);
38 if ($schema !== null) {
39 $schemas[strtolower($schema->tableName)] = $schema;
40 }
41 }
42
43 return $schemas;
44 }
45}
46