-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterfaceWriter.php
More file actions
118 lines (98 loc) · 3 KB
/
Copy pathInterfaceWriter.php
File metadata and controls
118 lines (98 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
namespace ProgrammatorDev\FluentValidator\Writer;
class InterfaceWriter
{
private \SplFileObject $file;
public function __construct(
private readonly string $interfaceName,
?string $outputDirectory = null,
)
{
$outputDirectory ??= dirname(__DIR__);
$filename = sprintf('%s/%s.php', rtrim($outputDirectory, '/'), $this->interfaceName);
$this->file = new \SplFileObject($filename, 'w');
}
public function writeLine(string $line = '', int $numIndent = 0): void
{
$this->writeIndent($numIndent);
$this->file->fwrite($line . PHP_EOL);
}
public function writeIndent(int $num = 1): void
{
$this->file->fwrite(str_repeat(' ', $num));
}
/**
* @param \ReflectionParameter[] $parameters
* @throws \ReflectionException
*/
public function writeMethod(string $name, string $returnType, array $parameters = [], bool $isStatic = false): void
{
$this->writeLine(
sprintf(
$isStatic ? 'public static function %s(' : 'public function %s(',
$name
),
1
);
foreach ($parameters as $parameter) {
$parameterType = $this->formatType((string) $parameter->getType());
if ($parameter->isOptional()) {
$this->writeLine(
sprintf(
'%s $%s = %s,',
$parameterType,
$parameter->getName(),
$this->formatValue($parameter->getDefaultValue())
),
2
);
}
else {
$this->writeLine(
sprintf(
'%s $%s,',
$parameterType,
$parameter->getName()
),
2
);
}
}
$this->writeLine(sprintf('): %s;', $this->formatType($returnType)), 1);
$this->writeLine();
}
public function writeNamespace(string $name): void
{
$this->writeLine(sprintf('namespace %s;', $name));
}
public function writeInterfaceStart(): void
{
$this->writeLine('<?php');
$this->writeLine();
$this->writeNamespace('ProgrammatorDev\FluentValidator');
$this->writeLine();
$this->writeLine(sprintf('interface %s', $this->interfaceName));
$this->writeLine('{');
}
public function writeInterfaceEnd(): void
{
$this->writeLine('}');
}
private function formatType(string $type): string
{
if (str_starts_with($type, 'Symfony')) {
return sprintf('\%s', $type);
}
return $type;
}
private function formatValue(mixed $value): string
{
if ($value === []) {
return '[]';
}
if ($value === null) {
return 'null';
}
return var_export($value, true);
}
}