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

AbstractFileCache::getAbsoluteCacheFilename()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.074

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 5
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 9
ccs 5
cts 6
cp 0.8333
crap 4.074
rs 10
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