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

DiCachedCompiler   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 92.59%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
dl 0
loc 66
ccs 25
cts 27
cp 0.9259
rs 10
c 1
b 0
f 0
wmc 13

8 Methods

Rating   Name   Duplication   Size   Complexity  
A processMethod() 0 3 1
A __construct() 0 8 2
A compiledClassExists() 0 3 1
A newInstance() 0 3 1
A validCache() 0 12 3
A generateCode() 0 3 1
A compile() 0 13 3
A writeCacheFile() 0 4 1
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