Test Failed
Push — master ( 1a9c2f...e3b3ac )
by Jelmer
01:56
created

DiCachedCompiler   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 84.62%

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 59
ccs 22
cts 26
cp 0.8462
rs 10
c 0
b 0
f 0
wmc 12

8 Methods

Rating   Name   Duplication   Size   Complexity  
A generateCode() 0 3 1
A newInstance() 0 3 1
A processMethod() 0 3 1
A __construct() 0 6 1
A validCache() 0 9 3
A compiledClassExists() 0 3 1
A compile() 0 12 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 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