Passed
Push — feature/rename-reset-cache-by-... ( 99a3ec )
by Jesús
04:26
created

ClassNameCache   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
eloc 20
dl 0
loc 66
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0

7 Methods

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