Completed
Push — master ( b1c200...f582f6 )
by Constantin
03:02
created

CodeGenerator::discoverAndPutContents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

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