Completed
Push — master ( 530066...874a85 )
by Constantin
03:00
created

CodeGenerator::deleteFileIfExists()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 4
cts 5
cp 0.8
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 4
nop 2
crap 3.072
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
    /**
15
     * @var MapCodeGenerator
16
     */
17
    private $codeGenerator;
18
19 6
    public function __construct(
20
        MapCodeGenerator $codeGenerator = null
21
    )
22
    {
23 6
        $this->codeGenerator = $codeGenerator ?? new MethodListenerMapperWriter;
24 6
    }
25
26 6
    public function discoverAndPutContents(
27
        Discoverer $discoverer,
28
        FileSystemInterface $fileSystem = null,
29
        string $commandSubscriberTemplateClassName,
30
        string $searchDirectory,
31
        string $outputFilePath,
32
        string $outputShortClassName = 'CommandHandlerSubscriber')
33
    {
34 6
        $fileSystem = $fileSystem ?? new OperatingSystemFileSystem();
35
36 6
        $classInfo = new \ReflectionClass($commandSubscriberTemplateClassName);
37
38 6
        $classInfo->getShortName();
39
40 6
        $this->deleteFileIfExists($fileSystem, $outputFilePath);
41
42 6
        $map = $discoverer->discover($searchDirectory);
43
44 5
        $template = file_get_contents($classInfo->getFileName());
45
46 5
        $template = str_replace($classInfo->getShortName() /*CommandSubscriberTemplate*/, $outputShortClassName /*CommandHandlerSubscriber*/, $template);
47
48 5
        $template = str_replace('--- This is just a template ---', '--- generated by ' . __FILE__ . ' at ' . date('c') . ' ---', $template);
49
50 5
        $code = $this->codeGenerator->generateAndGetFileContents($map, $template);
51
52 5
        $fileSystem->filePutContents($outputFilePath, $code);
53
54 5
        $fileSystem->fileSetPermissions($outputFilePath, 0777);
55 5
    }
56
57 6
    private function deleteFileIfExists(FileSystemInterface $fileSystem, string $outputFilePath)
58
    {
59
        try {
60 6
            if ($fileSystem->fileExists($outputFilePath)) {
61 6
                $fileSystem->fileDelete($outputFilePath);
62
            }
63
        } catch (\Exception $exception) {
64
            //it's ok
65
        }
66 6
    }
67
68
}