Passed
Push — master ( 1ef033...4ce446 )
by Jesús
09:47 queued 03:16
created

AbstractFileCache   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 65
rs 10
c 1
b 0
f 0
ccs 22
cts 22
cp 1
wmc 8

7 Methods

Rating   Name   Duplication   Size   Complexity  
A has() 0 3 1
A get() 0 3 1
A put() 0 10 1
A __construct() 0 4 1
A resetCache() 0 3 1
A getExistingCache() 0 12 2
A getAbsoluteCacheFilename() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\ClassResolver;
6
7
abstract class AbstractFileCache implements ClassNameCacheInterface
8
{
9
    /** @var array<string,string> */
10
    protected static array $cache = [];
11
12
    private string $cacheDir;
13
14 23
    public function __construct(string $cacheDir)
15
    {
16 23
        $this->cacheDir = $cacheDir;
17 23
        self::$cache = $this->getExistingCache();
18
    }
19
20
    /**
21
     * @internal
22
     */
23 8
    public static function resetCache(): void
24
    {
25 8
        self::$cache = [];
26
    }
27
28 23
    public function has(string $cacheKey): bool
29
    {
30 23
        return isset(self::$cache[$cacheKey]);
31
    }
32
33 7
    public function get(string $cacheKey): string
34
    {
35 7
        return self::$cache[$cacheKey];
36
    }
37
38 20
    public function put(string $cacheKey, string $className): void
39
    {
40 20
        self::$cache[$cacheKey] = $className;
41
42 20
        $fileContent = sprintf(
43
            '<?php return %s;',
44 20
            var_export(self::$cache, true)
45
        );
46
47 20
        file_put_contents($this->getAbsoluteCacheFilename(), $fileContent);
48
    }
49
50
    abstract protected function getCacheFilename(): string;
51
52
    /**
53
     * @return array<string,string>
54
     */
55 23
    private function getExistingCache(): array
56
    {
57 23
        $filename = $this->getAbsoluteCacheFilename();
58
59 23
        if (file_exists($filename)) {
60
            /** @var array<string,string> $content */
61 16
            $content = require $filename;
62
63 16
            return $content;
64
        }
65
66 16
        return [];
67
    }
68
69 23
    private function getAbsoluteCacheFilename(): string
70
    {
71 23
        return $this->cacheDir . $this->getCacheFilename();
72
    }
73
}
74