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