1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace jschreuder\MiddleDi; |
4
|
|
|
|
5
|
|
|
use OutOfRangeException; |
6
|
|
|
use ReflectionMethod; |
7
|
6 |
|
use SplFileObject; |
8
|
|
|
|
9
|
|
|
final class DiCachedCompiler implements DiCompilerInterface |
10
|
|
|
{ |
11
|
|
|
public function __construct( |
12
|
|
|
private DiCompilerInterface $compiler, |
13
|
6 |
|
private SplFileObject $file, |
14
|
|
|
private int $maxAge = 0 |
15
|
3 |
|
) |
16
|
|
|
{ |
17
|
3 |
|
} |
18
|
|
|
|
19
|
|
|
public function compiledClassExists(): bool |
20
|
2 |
|
{ |
21
|
|
|
return $this->compiler->compiledClassExists(); |
22
|
2 |
|
} |
23
|
1 |
|
|
24
|
|
|
public function compile(): void |
25
|
|
|
{ |
26
|
1 |
|
if ($this->compiledClassExists()) { |
27
|
1 |
|
throw new \RuntimeException('Cannot recompile already compiled container'); |
28
|
|
|
} |
29
|
|
|
|
30
|
1 |
|
if (!$this->validCache()) { |
31
|
1 |
|
$this->writeCacheFile($this->compiler->generateCode()); |
32
|
|
|
} |
33
|
|
|
|
34
|
1 |
|
include_once $this->file->getPath(); |
35
|
|
|
return; |
36
|
1 |
|
} |
37
|
1 |
|
|
38
|
|
|
private function writeCacheFile(string $code): void |
39
|
|
|
{ |
40
|
1 |
|
$this->file->ftruncate(0); |
41
|
1 |
|
$this->file->fwrite($code); |
42
|
|
|
} |
43
|
|
|
|
44
|
1 |
|
public function generateCode(): string |
45
|
|
|
{ |
46
|
1 |
|
return $this->compiler->generateCode(); |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
public function processMethod(ReflectionMethod $method): string |
50
|
|
|
{ |
51
|
1 |
|
return $this->compiler->processMethod($method); |
52
|
1 |
|
} |
53
|
|
|
|
54
|
|
|
private function validCache(): bool |
55
|
|
|
{ |
56
|
|
|
if (!$this->file->isFile()) { |
57
|
|
|
return false; |
58
|
|
|
} |
59
|
|
|
if ($this->maxAge <= 0) { |
60
|
1 |
|
throw new OutOfRangeException('Max age must be greater then zero.'); |
61
|
|
|
} |
62
|
1 |
|
return (time() - $this->file->getMTime()) < $this->maxAge; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function newInstance(array ...$args): mixed |
66
|
|
|
{ |
67
|
|
|
return $this->compiler->newInstance(...$args); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|