CodeGenerator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 2
crap 1
1
<?php
2
3
4
namespace Gica\Cqrs\CodeGeneration;
5
6
use Gica\CodeAnalysis\MethodListenerDiscovery\MapCodeGenerator;
7
use Gica\FileSystem\FileSystemInterface;
8
use Gica\FileSystem\OperatingSystemFileSystem;
9
10
class CodeGenerator
11
{
12
    /**
13
     * @var MapCodeGenerator
14
     */
15
    private $codeGenerator;
16
    /**
17
     * @var FileSystemInterface
18
     */
19
    private $fileSystem;
20
21 6
    public function __construct(
22
        MapCodeGenerator $codeGenerator,
23
        FileSystemInterface $fileSystem = null
24
    )
25
    {
26 6
        $this->codeGenerator = $codeGenerator;
27 6
        $this->fileSystem = $fileSystem ?? new OperatingSystemFileSystem();
28 6
    }
29
30 5
    public function discoverAndPutContents(
31
        array $map,
32
        string $templateClassName,
33
        string $outputFilePath,
34
        string $outputShortClassName)
35
    {
36
37 5
        $this->deleteFileIfExists($outputFilePath);
38
39 5
        $template = $this->loadTemplate($templateClassName, $outputShortClassName);
40
41 5
        $code = $this->codeGenerator->generateAndGetFileContents($map, $template);
42
43 5
        $this->fileSystem->filePutContents($outputFilePath, $code);
44
45 5
        $this->fileSystem->fileSetPermissions($outputFilePath, 0777);
46 5
    }
47
48 5
    private function deleteFileIfExists(string $outputFilePath)
49
    {
50 5
        if ($this->fileSystem->fileExists($outputFilePath)) {
51 1
            $this->fileSystem->fileDelete($outputFilePath);
52
        }
53 5
    }
54
55 5
    private function loadTemplate(string $templateClassName, string $outputShortClassName)
56
    {
57 5
        $classInfo = new \ReflectionClass($templateClassName);
58
59 5
        $template = file_get_contents($classInfo->getFileName());
60
61 5
        $template = str_replace($classInfo->getShortName(), $outputShortClassName, $template);
62
63 5
        $template = str_replace('--- This is just a template ---', '--- generated by ' . __FILE__ . ' at ' . date('c') . ' ---', $template);
64
65 5
        return $template;
66
    }
67
}