packages/sql-fixture/src/Provider/DdlFile.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlFixture\Provider;
6
7use RuntimeException;
8use SqlFixture\Schema\SchemaParseException;
9use SqlFixture\Schema\SchemaParserInterface;
10use SqlFixture\Schema\TableSchema;
11
12/**
13 * Reads a DDL file and rejects statements outside the schema grammar.
14 *
15 * @visibility root
16 */
17final class DdlFile
18{
19    /**
20     * Load a single SQL file.
21     * @throws RuntimeException
22     */
23    public function loadSchemaFile(string $filePath, SchemaParserInterface $parser): ?TableSchema
24    {
25        $content = file_get_contents($filePath);
26        if ($content === false) {
27            throw new RuntimeException("Failed to read file: {$filePath}");
28        }
29
30        $content = preg_replace('/--.*$/m', '', $content);
31        $content = preg_replace('/\/\*.*?\*\//s', '', $content ?? '');
32
33        if ($content === null || trim($content) === '') {
34            return null;
35        }
36
37        try {
38            $schema = $parser->parse($content);
39            return $schema;
40        } catch (SchemaParseException) {
41            return null;
42        }
43    }
44}
45