Passed
Push — feature/add-config-files ( 1c4158...837ed6 )
by Jesús
05:48 queued 02:26
created

AbstractFileCache   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Test Coverage

Coverage 96.15%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 71
ccs 25
cts 26
cp 0.9615
rs 10
wmc 11

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 9 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\ClassResolver;
6
7
use RuntimeException;
8
9
abstract class AbstractFileCache implements ClassNameCacheInterface
10
{
11
    /** @var array<string,string> */
12
    protected static array $cache = [];
13
14
    private string $cacheDir;
15
16 23
    public function __construct(string $cacheDir)
17
    {
18 23
        $this->cacheDir = $cacheDir;
19 23
        self::$cache = $this->getExistingCache();
20
    }
21
22
    /**
23
     * @internal
24
     */
25 8
    public static function resetCache(): void
26
    {
27 8
        self::$cache = [];
28
    }
29
30 23
    public function has(string $cacheKey): bool
31
    {
32 23
        return isset(self::$cache[$cacheKey]);
33
    }
34
35 7
    public function get(string $cacheKey): string
36
    {
37 7
        return self::$cache[$cacheKey];
38
    }
39
40 20
    public function put(string $cacheKey, string $className): void
41
    {
42 20
        self::$cache[$cacheKey] = $className;
43
44 20
        $fileContent = sprintf(
45
            '<?php return %s;',
46 20
            var_export(self::$cache, true)
47
        );
48
49 20
        file_put_contents($this->getAbsoluteCacheFilename(), $fileContent);
50
    }
51
52
    abstract protected function getCacheFilename(): string;
53
54
    /**
55
     * @return array<string,string>
56
     */
57 23
    private function getExistingCache(): array
58
    {
59 23
        $filename = $this->getAbsoluteCacheFilename();
60
61 23
        if (file_exists($filename)) {
62
            /** @var array<string,string> $content */
63 15
            $content = require $filename;
64
65 15
            return $content;
66
        }
67
68 17
        return [];
69
    }
70
71 23
    private function getAbsoluteCacheFilename(): string
72
    {
73 23
        if (!is_dir($this->cacheDir)
74 23
            && !mkdir($concurrentDirectory = $this->cacheDir)
75 23
            && !is_dir($concurrentDirectory)) {
76
            throw new RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
77
        }
78
79 23
        return $this->cacheDir . '/' . $this->getCacheFilename();
80
    }
81
}
82