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

AbstractFileCache   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Importance

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

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
    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