Passed
Push — feature/add-gacela-cli ( 2018fc )
by Chema
05:13 queued 15s
created

FileContentGenerator::generate()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 12
c 2
b 0
f 0
nc 4
nop 3
dl 0
loc 21
ccs 13
cts 13
cp 1
crap 3
rs 9.8666
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