FileContentGenerator::generate()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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