-
-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathCachedFileParser.php
More file actions
71 lines (53 loc) · 1.77 KB
/
CachedFileParser.php
File metadata and controls
71 lines (53 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
declare(strict_types=1);
namespace Arkitect\Analyzer;
class CachedFileParser implements Parser
{
/** @var array<string, array{hash: string, result: ParserResult}> */
private array $entries = [];
private bool $dirty = false;
private string $filePath;
private Parser $innerParser;
public function __construct(Parser $innerParser, string $cacheFilePath)
{
$this->filePath = $cacheFilePath;
$this->innerParser = $innerParser;
if (file_exists($cacheFilePath)) {
$data = unserialize((string) file_get_contents($cacheFilePath));
if (\is_array($data)) {
$this->entries = $data;
}
}
}
public function __destruct()
{
if ($this->dirty) {
file_put_contents($this->filePath, serialize($this->entries));
}
}
public function parse(string $fileContent, string $filename): ParserResult
{
$cachedResult = $this->get($filename, md5($fileContent));
if (null !== $cachedResult) {
return $cachedResult;
}
$result = $this->innerParser->parse($fileContent, $filename);
$this->set($filename, md5($fileContent), $result);
return $result;
}
public function get(string $filename, string $contentHash): ?ParserResult
{
if (!isset($this->entries[$filename])) {
return null;
}
if ($this->entries[$filename]['hash'] !== $contentHash) {
return null;
}
return $this->entries[$filename]['result'];
}
public function set(string $filename, string $contentHash, ParserResult $result): void
{
$this->entries[$filename] = ['hash' => $contentHash, 'result' => $result];
$this->dirty = true;
}
}