forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCachedParser.php
More file actions
102 lines (81 loc) · 2.44 KB
/
Copy pathCachedParser.php
File metadata and controls
102 lines (81 loc) · 2.44 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
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
98
99
100
101
102
<?php declare(strict_types = 1);
namespace PHPStan\Parser;
use PHPStan\File\FileReader;
class CachedParser implements Parser
{
private \PHPStan\Parser\Parser $originalParser;
/** @var array<string, \PhpParser\Node\Stmt[]>*/
private array $cachedNodesByString = [];
private int $cachedNodesByStringCount = 0;
private int $cachedNodesByStringCountMax;
/** @var array<string, true> */
private array $parsedByString = [];
public function __construct(
Parser $originalParser,
int $cachedNodesByStringCountMax
)
{
$this->originalParser = $originalParser;
$this->cachedNodesByStringCountMax = $cachedNodesByStringCountMax;
}
/**
* @param string $file path to a file to parse
* @return \PhpParser\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];
}
/**
* @param string $sourceCode
* @return \PhpParser\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, \PhpParser\Node[]>
*/
public function getCachedNodesByString(): array
{
return $this->cachedNodesByString;
}
}