Test Setup Failed
Push — feature/custom-services-cache ( f75830 )
by Chema
29:27
created

AbstractFileCache::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 1
b 0
f 0
cc 1
nc 1
nop 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
    public function __construct(string $cacheDir)
15
    {
16
        $this->cacheDir = $cacheDir;
17
        self::$cache = $this->getExistingCache();
18
    }
19
20
    /**
21
     * @internal
22
     */
23
    public static function resetCache(): void
24
    {
25
        self::$cache = [];
26
    }
27
28
    public function has(string $cacheKey): bool
29
    {
30
        return isset(self::$cache[$cacheKey]);
31
    }
32
33
    public function get(string $cacheKey): string
34
    {
35
        return self::$cache[$cacheKey];
36
    }
37
38
    public function put(string $cacheKey, string $className): void
39
    {
40
        self::$cache[$cacheKey] = $className;
41
42
        $fileContent = sprintf(
43
            '<?php return %s;',
44
            var_export(self::$cache, true)
45
        );
46
47
        file_put_contents($this->getAbsoluteCacheFilename(), $fileContent);
48
    }
49
50
    abstract protected function getCacheFilename(): string;
51
52
    /**
53
     * @return array<string,string>
54
     */
55
    private function getExistingCache(): array
56
    {
57
        $filename = $this->getAbsoluteCacheFilename();
58
59
        if (file_exists($filename)) {
60
            /** @var array<string,string> $content */
61
            $content = require $filename;
62
63
            return $content;
64
        }
65
66
        return [];
67
    }
68
69
    private function getAbsoluteCacheFilename(): string
70
    {
71
        return $this->cacheDir . $this->getCacheFilename();
72
    }
73
}
74