FileMaterializer   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 65
rs 10
c 0
b 0
f 0
wmc 7
lcom 1
cbo 1

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A materialize() 0 12 3
A makeFilename() 0 4 1
A prepareCode() 0 4 1
A create() 0 4 1
1
<?php
2
3
/**
4
 * Spiral Framework. Cycle ProxyFactory
5
 *
6
 * @license MIT
7
 * @author  Valentin V (Vvval)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Cycle\ORM\Promise\Materizalizer;
13
14
use Cycle\ORM\Promise\MaterializerInterface;
15
use Exception;
16
use ReflectionClass;
17
use Spiral\Core\Container\SingletonInterface;
18
19
use function Cycle\ORM\Promise\trimPHPOpenTag;
20
21
final class FileMaterializer implements MaterializerInterface, SingletonInterface
22
{
23
    /** @var ModificationInspector */
24
    private $inspector;
25
26
    /** @var string */
27
    private $directory;
28
29
    /** @var array */
30
    private $materialized = [];
31
32
    /**
33
     * @param ModificationInspector $inspector
34
     * @param string                $directory
35
     */
36
    public function __construct(ModificationInspector $inspector, string $directory)
37
    {
38
        $this->inspector = $inspector;
39
        $this->directory = $directory;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     * @throws Exception
45
     */
46
    public function materialize(string $code, string $shortClassName, ReflectionClass $reflection): void
47
    {
48
        $modifiedDate = $this->inspector->getLastModifiedDate($reflection);
49
        $filename = $this->makeFilename($shortClassName);
50
51
        if (!isset($this->materialized[$filename]) || $this->materialized[$filename] < $modifiedDate) {
52
            $this->materialized[$filename] = $modifiedDate;
53
            $this->create($filename, $this->prepareCode($code));
54
55
            require_once($filename);
56
        }
57
    }
58
59
    /**
60
     * @param string $className
61
     * @return string
62
     */
63
    private function makeFilename(string $className): string
64
    {
65
        return $this->directory . DIRECTORY_SEPARATOR . $className . '.php';
66
    }
67
68
    /**
69
     * @param string $code
70
     * @return string
71
     */
72
    private function prepareCode(string $code): string
73
    {
74
        return "<?php\n" . trim(trimPHPOpenTag($code));
75
    }
76
77
    /**
78
     * @param string $filename
79
     * @param string $code
80
     */
81
    private function create(string $filename, string $code): void
82
    {
83
        file_put_contents($filename, $code);
84
    }
85
}
86