-
Notifications
You must be signed in to change notification settings - Fork 428
/
OptimizedDirectorySourceLocator.php
254 lines (213 loc) · 7.23 KB
/
OptimizedDirectorySourceLocator.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
<?php declare(strict_types = 1);
namespace PHPStan\Reflection\BetterReflection\SourceLocator;
use PhpParser\Node;
use PHPStan\BetterReflection\Identifier\Identifier;
use PHPStan\BetterReflection\Identifier\IdentifierType;
use PHPStan\BetterReflection\Reflection\Reflection;
use PHPStan\BetterReflection\Reflector\Reflector;
use PHPStan\BetterReflection\SourceLocator\Ast\Strategy\NodeToReflection;
use PHPStan\BetterReflection\SourceLocator\Type\SourceLocator;
use PHPStan\Php\PhpVersion;
use PHPStan\ShouldNotHappenException;
use function array_key_exists;
use function array_merge;
use function count;
use function php_strip_whitespace;
use function preg_match_all;
use function sprintf;
use function strtolower;
class OptimizedDirectorySourceLocator implements SourceLocator
{
private PhpFileCleaner $cleaner;
private string $extraTypes;
/** @var array<string, string>|null */
private ?array $classToFile = null;
/** @var array<string, array<int, string>>|null */
private ?array $functionToFiles = null;
/** @var array<string, FetchedNode<Node\Stmt\ClassLike>> */
private array $classNodes = [];
/** @var array<string, FetchedNode<Node\Stmt\Function_>> */
private array $functionNodes = [];
/**
* @param string[] $files
*/
public function __construct(
private FileNodesFetcher $fileNodesFetcher,
private PhpVersion $phpVersion,
private array $files,
)
{
$extraTypes = '';
$extraTypesArray = [];
if ($this->phpVersion->supportsEnums()) {
$extraTypes = '|enum';
$extraTypesArray[] = 'enum';
}
$this->extraTypes = $extraTypes;
$this->cleaner = new PhpFileCleaner(array_merge(['class', 'interface', 'trait', 'function'], $extraTypesArray));
}
public function locateIdentifier(Reflector $reflector, Identifier $identifier): ?Reflection
{
if ($identifier->isClass()) {
$className = strtolower($identifier->getName());
if (array_key_exists($className, $this->classNodes)) {
return $this->nodeToReflection($reflector, $this->classNodes[$className]);
}
$file = $this->findFileByClass($className);
if ($file === null) {
return null;
}
$fetchedNodesResult = $this->fileNodesFetcher->fetchNodes($file);
foreach ($fetchedNodesResult->getClassNodes() as $identifierName => $fetchedClassNodes) {
foreach ($fetchedClassNodes as $fetchedClassNode) {
$this->classNodes[$identifierName] = $fetchedClassNode;
break;
}
}
if (!array_key_exists($className, $this->classNodes)) {
return null;
}
return $this->nodeToReflection($reflector, $this->classNodes[$className]);
}
if ($identifier->isFunction()) {
$functionName = strtolower($identifier->getName());
if (array_key_exists($functionName, $this->functionNodes)) {
return $this->nodeToReflection($reflector, $this->functionNodes[$functionName]);
}
$files = $this->findFilesByFunction($functionName);
foreach ($files as $file) {
$fetchedNodesResult = $this->fileNodesFetcher->fetchNodes($file);
foreach ($fetchedNodesResult->getFunctionNodes() as $identifierName => $fetchedFunctionNode) {
$this->functionNodes[$identifierName] = $fetchedFunctionNode;
}
}
if (!array_key_exists($functionName, $this->functionNodes)) {
return null;
}
return $this->nodeToReflection($reflector, $this->functionNodes[$functionName]);
}
return null;
}
/**
* @param FetchedNode<Node\Stmt\ClassLike>|FetchedNode<Node\Stmt\Function_> $fetchedNode
*/
private function nodeToReflection(Reflector $reflector, FetchedNode $fetchedNode): Reflection
{
$nodeToReflection = new NodeToReflection();
return $nodeToReflection->__invoke(
$reflector,
$fetchedNode->getNode(),
$fetchedNode->getLocatedSource(),
$fetchedNode->getNamespace(),
);
}
private function findFileByClass(string $className): ?string
{
if ($this->classToFile === null) {
$this->init();
if ($this->classToFile === null) {
throw new ShouldNotHappenException();
}
}
if (!array_key_exists($className, $this->classToFile)) {
return null;
}
return $this->classToFile[$className];
}
/**
* @return string[]
*/
private function findFilesByFunction(string $functionName): array
{
if ($this->functionToFiles === null) {
$this->init();
if ($this->functionToFiles === null) {
throw new ShouldNotHappenException();
}
}
if (!array_key_exists($functionName, $this->functionToFiles)) {
return [];
}
return $this->functionToFiles[$functionName];
}
private function init(): void
{
$classToFile = [];
$functionToFiles = [];
foreach ($this->files as $file) {
$symbols = $this->findSymbols($file);
$classesInFile = $symbols['classes'];
$functionsInFile = $symbols['functions'];
foreach ($classesInFile as $classInFile) {
$classToFile[$classInFile] = $file;
}
foreach ($functionsInFile as $functionInFile) {
if (!array_key_exists($functionInFile, $functionToFiles)) {
$functionToFiles[$functionInFile] = [];
}
$functionToFiles[$functionInFile][] = $file;
}
}
$this->classToFile = $classToFile;
$this->functionToFiles = $functionToFiles;
}
/**
* Inspired by Composer\Autoload\ClassMapGenerator::findClasses()
* @link https://github.com/composer/composer/blob/45d3e133a4691eccb12e9cd6f9dfd76eddc1906d/src/Composer/Autoload/ClassMapGenerator.php#L216
*
* @return array{classes: string[], functions: string[]}
*/
private function findSymbols(string $file): array
{
$contents = @php_strip_whitespace($file);
if ($contents === '') {
return ['classes' => [], 'functions' => []];
}
$matchResults = (bool) preg_match_all(sprintf('{\b(?:class|interface|trait|function%s)\s}i', $this->extraTypes), $contents, $matches);
if (!$matchResults) {
return ['classes' => [], 'functions' => []];
}
$contents = $this->cleaner->clean($contents, count($matches[0]));
preg_match_all(sprintf('{
(?:
\b(?<![\$:>])(?P<type>class|interface|trait|function%s) \s++ (?P<byref>&\s*)? (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*+)
| \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s++[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\s*+\\\\\s*+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+)? \s*+ [\{;]
)
}ix', $this->extraTypes), $contents, $matches);
$classes = [];
$functions = [];
$namespace = '';
for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
if (!empty($matches['ns'][$i])) { // phpcs:disable
$namespace = str_replace([' ', "\t", "\r", "\n"], '', $matches['nsname'][$i]) . '\\';
} else {
$name = $matches['name'][$i];
// skip anon classes extending/implementing
if ($name === 'extends' || $name === 'implements') {
continue;
}
$namespacedName = strtolower(ltrim($namespace . $name, '\\'));
$lowerType = strtolower($matches['type'][$i]);
if ($lowerType === 'function') {
$functions[] = $namespacedName;
} else {
if ($lowerType === 'enum') {
$colonPos = strrpos($namespacedName, ':');
if (false !== $colonPos) {
$namespacedName = substr($namespacedName, 0, $colonPos);
}
}
$classes[] = $namespacedName;
}
}
}
return [
'classes' => $classes,
'functions' => $functions,
];
}
public function locateIdentifiersByType(Reflector $reflector, IdentifierType $identifierType): array
{
return [];
}
}