FileContentGenerator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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