packages/sql-faker/tests/Unit/Compiler/Resource/GrammarWriterTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\SqlFaker\Compiler\Resource;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\UsesClass;
9use PHPUnit\Framework\TestCase;
10use RuntimeException;
11use SqlFaker\Compiler\Resource\ArtifactDirectory;
12use SqlFaker\Compiler\Resource\GrammarWriter;
13use SqlFaker\Grammar\Resource\SqlVersion;
14
15#[CoversClass(GrammarWriter::class)]
16#[UsesClass(ArtifactDirectory::class)]
17#[UsesClass(SqlVersion::class)]
18final class GrammarWriterTest extends TestCase
19{
20    public function testPublishReplacesTheCompleteAstAndCleansItsStagingFile(): void
21    {
22        $directory = sys_get_temp_dir() . '/sql-faker-ast-' . bin2hex(random_bytes(8));
23        $path = $directory . '/ast.php';
24        $version = new SqlVersion('mysql', 'mysql-8.4.7', $path);
25        try {
26            $writer = new GrammarWriter();
27            $writer->publish($version, '<?php return "old";');
28            $writer->publish($version, '<?php return "new";');
29            self::assertSame('<?php return "new";', file_get_contents($path));
30            self::assertSame(['.', '..', 'ast.php'], scandir($directory));
31        } finally {
32            unlink($path);
33            rmdir($directory);
34        }
35    }
36
37    public function testPublishFailsBeforeStagingWhenTheParentIsAFile(): void
38    {
39        $parent = tempnam(sys_get_temp_dir(), 'sql-faker-parent-');
40        self::assertNotFalse($parent);
41        try {
42            $this->expectException(RuntimeException::class);
43            (new GrammarWriter())->publish(new SqlVersion('mysql', 'mysql-8.4.7', $parent . '/ast.php'), 'ast');
44        } finally {
45            unlink($parent);
46        }
47    }
48}
49