Passed
Push — master ( 4ba5d0...423aca )
by Valentin
02:37
created

FileMaterializer::prepareCode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Cycle\ORM\Promise\Materizalizer;
5
6
use Cycle\ORM\Promise\Declaration\Declaration;
7
use Cycle\ORM\Promise\MaterializerInterface;
8
use Spiral\Core\Container\SingletonInterface;
9
10
class FileMaterializer implements MaterializerInterface, SingletonInterface
11
{
12
    /** @var ModificationInspector */
13
    private $inspector;
14
15
    /** @var string */
16
    private $directory;
17
18
    /** @var array */
19
    private $materialized = [];
20
21
    public function __construct(ModificationInspector $inspector, string $directory)
22
    {
23
        $this->inspector = $inspector;
24
        $this->directory = $directory;
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function materialize(string $code, Declaration $declaration, \ReflectionClass $reflection): void
31
    {
32
        if (class_exists($declaration->class->getFullName())) {
33
            return;
34
        }
35
36
        $modifiedDate = $this->inspector->getLastModifiedDate($reflection);
37
        $filename = $this->makeFilename($declaration);
38
39
        if (!isset($this->materialized[$filename]) || $this->materialized[$filename] < $modifiedDate) {
40
            $this->materialized[$filename] = $modifiedDate;
41
            $this->create($filename, $code);
42
        }
43
    }
44
45
    private function makeFilename(Declaration $declaration): string
46
    {
47
        return $this->directory . DIRECTORY_SEPARATOR . $this->convertName($declaration);
48
    }
49
50
    private function convertName(Declaration $declaration): string
51
    {
52
        return str_replace('\\', '', $declaration->class->getFullName());
53
    }
54
55
    private function create(string $filename, string $code): void
56
    {
57
        file_put_contents($filename, $code);
58
    }
59
}