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

AbstractFileCache::get()   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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
ccs 2
cts 2
cp 1
crap 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