Passed
Push — feature/gacela-cached-class-na... ( 44c645 )
by Chema
26:13
created

ClassNameCache::getCachedFilename()   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
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
cc 1
nc 1
nop 0
crap 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 21
    public function __construct(string $cachedClassNamesDir)
17
    {
18 21
        $this->cachedClassNamesDir = $cachedClassNamesDir;
19
20 21
        self::$cachedClassNames = $this->getCachedClassNames();
21
    }
22
23
    /**
24
     * @internal
25
     */
26 8
    public static function resetCachedClassNames(): void
27
    {
28 8
        self::$cachedClassNames = [];
29
    }
30
31 21
    public function has(string $cacheKey): bool
32
    {
33 21
        return isset(self::$cachedClassNames[$cacheKey]);
34
    }
35
36
    public function get(string $cacheKey): string
37
    {
38
        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 21
    private function getCachedClassNames(): array
57
    {
58 21
        $filename = $this->getCachedFilename();
59
60 21
        if (file_exists($filename)) {
61
            /** @var array<string,string> $content */
62 15
            $content = require $filename;
63
64 15
            return $content;
65
        }
66
67 15
        return [];
68
    }
69
70 21
    private function getCachedFilename(): string
71
    {
72 21
        return $this->cachedClassNamesDir . self::CACHED_CLASS_NAMES_FILE;
73
    }
74
}
75