1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Cycle\ORM\Promise\Materizalizer; |
5
|
|
|
|
6
|
|
|
use Cycle\ORM\Promise\MaterializerInterface; |
7
|
|
|
use Spiral\Core\Container\SingletonInterface; |
8
|
|
|
|
9
|
|
|
class FileMaterializer implements MaterializerInterface, SingletonInterface |
10
|
|
|
{ |
11
|
|
|
/** @var ModificationInspector */ |
12
|
|
|
private $inspector; |
13
|
|
|
|
14
|
|
|
/** @var string */ |
15
|
|
|
private $directory; |
16
|
|
|
|
17
|
|
|
/** @var array */ |
18
|
|
|
private $materialized = []; |
19
|
|
|
|
20
|
|
|
public function __construct(ModificationInspector $inspector, string $directory) |
21
|
|
|
{ |
22
|
|
|
$this->inspector = $inspector; |
23
|
|
|
$this->directory = $directory; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
*/ |
29
|
|
|
public function materialize(string $code, string $shortClassName, \ReflectionClass $reflection): void |
30
|
|
|
{ |
31
|
|
|
$modifiedDate = $this->inspector->getLastModifiedDate($reflection); |
32
|
|
|
$filename = $this->makeFilename($shortClassName); |
33
|
|
|
|
34
|
|
|
if (!isset($this->materialized[$filename]) || $this->materialized[$filename] < $modifiedDate) { |
35
|
|
|
$this->materialized[$filename] = $modifiedDate; |
36
|
|
|
$this->create($filename, $this->prepareCode($code)); |
37
|
|
|
|
38
|
|
|
require_once($filename); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
private function makeFilename(string $className): string |
43
|
|
|
{ |
44
|
|
|
return $this->directory . DIRECTORY_SEPARATOR . $className . '.php'; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
View Code Duplication |
private function prepareCode(string $code): string |
|
|
|
|
48
|
|
|
{ |
49
|
|
|
if (mb_strpos($code, '<?php') === 0) { |
50
|
|
|
$code = mb_substr($code, 5); |
51
|
|
|
} elseif (mb_strpos($code, '<?') === 0) { |
52
|
|
|
$code = mb_substr($code, 2); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return "<?php\n" . trim($code); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
private function create(string $filename, string $code): void |
59
|
|
|
{ |
60
|
|
|
file_put_contents($filename, $code); |
61
|
|
|
} |
62
|
|
|
} |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.