Passed
Push — master ( 24b216...683720 )
by Jelmer
11:28
created

DiCachedCompiler::newInstance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace jschreuder\MiddleDi;
4
5
use OutOfRangeException;
6
use ReflectionMethod;
7
use SplFileObject;
8
9
final class DiCachedCompiler implements DiCompilerInterface
10
{
11 10
    public function __construct(
12
        private DiCompilerInterface $compiler,
13
        private SplFileObject $file,
14
        private int $maxAge = 0
15
    )
16
    {
17 10
        if ($maxAge < 0) {
18 1
            throw new OutOfRangeException('Max age must be greater then zero.');
19
        }
20
    }
21
22 6
    public function compiledClassExists(): bool
23
    {
24 6
        return $this->compiler->compiledClassExists();
25
    }
26
27 5
    public function compile(): static
28
    {
29 5
        if ($this->compiledClassExists()) {
30 1
            throw new \RuntimeException('Cannot recompile already compiled container');
31
        }
32
33 4
        if (!$this->validCache()) {
34 2
            $this->writeCacheFile($this->compiler->generateCode());
35
        }
36
37 4
        include $this->file->getPath();
38
        
39 4
        return $this;
40
    }
41
42 2
    private function writeCacheFile(string $code): void
43
    {
44 2
        $this->file->ftruncate(0);
45 2
        $this->file->fwrite($code);
46
    }
47
48 1
    public function generateCode(): string
49
    {
50 1
        return $this->compiler->generateCode();
51
    }
52
53
    public function processMethod(ReflectionMethod $method): string
54
    {
55
        return $this->compiler->processMethod($method);
56
    }
57
58 4
    private function validCache(): bool
59
    {
60
        // Return false if there's no file cached
61 4
        if (!$this->file->isFile()) {
62 1
            return false;
63
        }
64
        // There is a file, when max-age is set to zero it will always be valid
65 3
        if ($this->maxAge === 0) {
66 1
            return true;
67
        }
68
        // Otherwise return true/false based on if it is older then allowed
69 2
        return (time() - $this->file->getMTime()) < $this->maxAge;
70
    }
71
72 1
    public function newInstance(array ...$args): mixed
73
    {
74 1
        return $this->compiler->newInstance(...$args);
75
    }
76
}
77