Skip to content

Commit 475bb48

Browse files
committed
refactor(writer): harden interface generation
1 parent eb17b77 commit 475bb48

2 files changed

Lines changed: 50 additions & 16 deletions

File tree

src/Writer/InterfaceWriter.php

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,14 @@ class InterfaceWriter
66
{
77
private \SplFileObject $file;
88

9-
public function __construct(private readonly string $interfaceName)
9+
public function __construct(
10+
private readonly string $interfaceName,
11+
?string $outputDirectory = null,
12+
)
1013
{
11-
$filename = sprintf('src/%s.php', $this->interfaceName);
14+
$outputDirectory ??= dirname(__DIR__);
15+
$filename = sprintf('%s/%s.php', rtrim($outputDirectory, '/'), $this->interfaceName);
16+
1217
$this->file = new \SplFileObject($filename, 'w');
1318
}
1419

@@ -100,10 +105,6 @@ private function formatType(string $type): string
100105

101106
private function formatValue(mixed $value): string
102107
{
103-
if (is_string($value)) {
104-
return sprintf("'%s'", $value);
105-
}
106-
107108
if ($value === []) {
108109
return '[]';
109110
}
@@ -112,14 +113,6 @@ private function formatValue(mixed $value): string
112113
return 'null';
113114
}
114115

115-
if ($value === false) {
116-
return 'false';
117-
}
118-
119-
if ($value === true) {
120-
return 'true';
121-
}
122-
123-
return (string) $value;
116+
return var_export($value, true);
124117
}
125-
}
118+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
namespace ProgrammatorDev\FluentValidator\Test\Writer;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use ProgrammatorDev\FluentValidator\Writer\InterfaceWriter;
7+
8+
class InterfaceWriterTest extends TestCase
9+
{
10+
public function testWritesToConfiguredOutputDirectoryAndEscapesDefaultValues(): void
11+
{
12+
$outputDirectory = sys_get_temp_dir() . '/fluent-validator-' . bin2hex(random_bytes(8));
13+
mkdir($outputDirectory);
14+
15+
$filePath = $outputDirectory . '/ExampleInterface.php';
16+
17+
try {
18+
$parameters = (new \ReflectionFunction(
19+
fn (string $message = "It's valid", array $groups = [], mixed $payload = null) => null
20+
))->getParameters();
21+
22+
$writer = new InterfaceWriter('ExampleInterface', $outputDirectory);
23+
$writer->writeInterfaceStart();
24+
$writer->writeMethod('example', 'Validator', $parameters);
25+
$writer->writeInterfaceEnd();
26+
27+
$contents = file_get_contents($filePath);
28+
29+
$this->assertStringContainsString("string \$message = 'It\\'s valid',", $contents);
30+
$this->assertStringContainsString('array $groups = [],', $contents);
31+
$this->assertStringContainsString('mixed $payload = null,', $contents);
32+
}
33+
finally {
34+
if (is_file($filePath)) {
35+
unlink($filePath);
36+
}
37+
38+
rmdir($outputDirectory);
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)