|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Gacela\CodeGenerator\Domain\FileContent; |
|
6
|
|
|
|
|
7
|
|
|
use Gacela\CodeGenerator\Domain\CommandArguments\CommandArguments; |
|
8
|
|
|
use RuntimeException; |
|
9
|
|
|
|
|
10
|
|
|
final class FileContentGenerator implements FileContentGeneratorInterface |
|
11
|
|
|
{ |
|
12
|
|
|
private FileContentIoInterface $fileContentIo; |
|
13
|
|
|
|
|
14
|
|
|
/** @var array<string,string> */ |
|
15
|
|
|
private array $templateByFilenameMap; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @param array<string,string> $templateByFilenameMap |
|
19
|
|
|
*/ |
|
20
|
5 |
|
public function __construct( |
|
21
|
|
|
FileContentIoInterface $fileContentIo, |
|
22
|
|
|
array $templateByFilenameMap |
|
23
|
|
|
) { |
|
24
|
5 |
|
$this->fileContentIo = $fileContentIo; |
|
25
|
5 |
|
$this->templateByFilenameMap = $templateByFilenameMap; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @return string path result where the file was generated |
|
30
|
|
|
*/ |
|
31
|
5 |
|
public function generate(CommandArguments $commandArguments, string $filename, bool $withShortName = false): string |
|
32
|
|
|
{ |
|
33
|
5 |
|
$this->fileContentIo->mkdir($commandArguments->directory()); |
|
34
|
|
|
|
|
35
|
5 |
|
$moduleName = $withShortName ? '' : $commandArguments->basename(); |
|
36
|
5 |
|
$className = $moduleName . $filename; |
|
37
|
|
|
|
|
38
|
5 |
|
$path = sprintf('%s/%s.php', $commandArguments->directory(), $className); |
|
39
|
5 |
|
$search = ['$NAMESPACE$', '$MODULE_NAME$', '$CLASS_NAME$']; |
|
40
|
5 |
|
$replace = [$commandArguments->namespace(), $moduleName, $className]; |
|
41
|
|
|
|
|
42
|
5 |
|
$template = $this->templateByFilenameMap[$filename] ?? ''; |
|
43
|
5 |
|
if (empty($template)) { |
|
44
|
1 |
|
throw new RuntimeException("Unknown template for '{$filename}'?"); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
4 |
|
$fileContent = str_replace($search, $replace, $template); |
|
48
|
|
|
|
|
49
|
4 |
|
$this->fileContentIo->filePutContents($path, $fileContent); |
|
50
|
|
|
|
|
51
|
4 |
|
return $path; |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|