-
Notifications
You must be signed in to change notification settings - Fork 483
/
Copy pathCachedParser.php
97 lines (78 loc) · 2.23 KB
/
CachedParser.php
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php declare(strict_types = 1);
namespace PHPStan\Parser;
use PhpParser\Node;
use PHPStan\File\FileReader;
use function array_slice;
class CachedParser implements Parser
{
/** @var array<string, Node\Stmt[]>*/
private array $cachedNodesByString = [];
private int $cachedNodesByStringCount = 0;
/** @var array<string, true> */
private array $parsedByString = [];
public function __construct(
private Parser $originalParser,
private int $cachedNodesByStringCountMax,
)
{
}
/**
* @param string $file path to a file to parse
* @return Node\Stmt[]
*/
public function parseFile(string $file): array
{
if ($this->cachedNodesByStringCountMax !== 0 && $this->cachedNodesByStringCount >= $this->cachedNodesByStringCountMax) {
$this->cachedNodesByString = array_slice(
$this->cachedNodesByString,
1,
null,
true,
);
--$this->cachedNodesByStringCount;
}
$sourceCode = FileReader::read($file);
if (!isset($this->cachedNodesByString[$sourceCode]) || isset($this->parsedByString[$sourceCode])) {
$this->cachedNodesByString[$sourceCode] = $this->originalParser->parseFile($file);
$this->cachedNodesByStringCount++;
unset($this->parsedByString[$sourceCode]);
}
return $this->cachedNodesByString[$sourceCode];
}
/**
* @return Node\Stmt[]
*/
public function parseString(string $sourceCode): array
{
if ($this->cachedNodesByStringCountMax !== 0 && $this->cachedNodesByStringCount >= $this->cachedNodesByStringCountMax) {
$this->cachedNodesByString = array_slice(
$this->cachedNodesByString,
1,
null,
true,
);
--$this->cachedNodesByStringCount;
}
if (!isset($this->cachedNodesByString[$sourceCode])) {
$this->cachedNodesByString[$sourceCode] = $this->originalParser->parseString($sourceCode);
$this->cachedNodesByStringCount++;
$this->parsedByString[$sourceCode] = true;
}
return $this->cachedNodesByString[$sourceCode];
}
public function getCachedNodesByStringCount(): int
{
return $this->cachedNodesByStringCount;
}
public function getCachedNodesByStringCountMax(): int
{
return $this->cachedNodesByStringCountMax;
}
/**
* @return array<string, Node[]>
*/
public function getCachedNodesByString(): array
{
return $this->cachedNodesByString;
}
}