Repository navigation
Expand file tree
/
Copy pathCachedPhpInternalSourceLocator.php
More file actions
226 lines (195 loc) · 7.58 KB
/
Copy pathCachedPhpInternalSourceLocator.php
File metadata and controls
226 lines (195 loc) · 7.58 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
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
<?php declare(strict_types = 1);
namespace PHPStan\Reflection\BetterReflection\SourceLocator;
use Override;
use PHPStan\BetterReflection\Identifier\Identifier;
use PHPStan\BetterReflection\Identifier\IdentifierType;
use PHPStan\BetterReflection\Reflection\Reflection;
use PHPStan\BetterReflection\Reflection\ReflectionClass;
use PHPStan\BetterReflection\Reflection\ReflectionConstant;
use PHPStan\BetterReflection\Reflection\ReflectionEnum;
use PHPStan\BetterReflection\Reflection\ReflectionFunction;
use PHPStan\BetterReflection\Reflector\Reflector;
use PHPStan\BetterReflection\SourceLocator\SourceStubber\PhpStormStubsSourceStubber;
use PHPStan\BetterReflection\SourceLocator\Type\SourceLocator;
use PHPStan\Cache\Cache;
use PHPStan\Internal\ComposerHelper;
use PHPStan\Php\PhpVersion;
use PHPStan\Reflection\BetterReflection\SourceStubber\ExtensionVersionProvider;
use function array_key_exists;
use function is_array;
use function is_file;
use function is_string;
use function sprintf;
use function str_starts_with;
use function strlen;
use function strpos;
use function strtolower;
use function substr;
/**
* Caches the reflections built from the PhpStorm stubs the way the optimized
* locators cache userland ones. PHP built-in classes never had a cache, so
* every process parsed the stub files and rebuilt the same reflections again;
* with this in place they are built once, persisted like any other cache
* entry, and shared across a run's parallel workers through the arena.
*
* The stubber's output depends on the stubs package, the reflection library
* and the target PHP and extension versions (stub members are version-filtered),
* so all four are part of the cache key.
*
* The exported blob contains the absolute path of the stub file, but the
* cache key deliberately contains no paths - the same entries are shared by
* every PHPStan installation with the same package versions, and survive the
* installation being moved. The path is therefore stored relative to the
* phpstorm-stubs package root and resolved against the current installation
* on import (https://github.com/phpstan/phpstan/issues/15023).
*/
final class CachedPhpInternalSourceLocator implements SourceLocator
{
private const STUBS_DIR_MARKER = '/jetbrains/phpstorm-stubs/';
private const RELATIVE_FILENAME_PREFIX = 'phpstorm-stubs:';
private ?string $variableCacheKey = null;
private ?string $stubsRootDir = null;
public function __construct(
private SourceLocator $inner,
private Cache $cache,
private PhpVersion $phpVersion,
private PhpStormStubsSourceStubber $stubber,
private ExtensionVersionProvider $extensionVersionProvider,
)
{
}
#[Override]
public function locateIdentifier(Reflector $reflector, Identifier $identifier): ?Reflection
{
$name = $identifier->getName();
if ($identifier->isClass() || $identifier->isFunction()) {
$name = strtolower($name);
}
// Almost everything that reaches this locator is a userland class name
// that every earlier locator failed to resolve, and a name the stubs do
// not have can never have been cached - the stubber is the only source
// the wrapped locator reads from. Ruling those out against the stubs map
// is an array lookup, where asking the cache means hashing the key and
// stat()ing a file that will never exist. The wrapped locator is still
// asked: it resolves class aliases before consulting the stubber, so it
// can answer for a name the map does not list - such an answer just does
// not get cached, under a key that would be the alias anyway.
if ($identifier->isClass() && !$this->stubber->hasClass($name)) {
return $this->inner->locateIdentifier($reflector, $identifier);
}
$cacheKey = sprintf('phpinternal-%s-%s', $identifier->getType()->getName(), $name);
$variableCacheKey = $this->getVariableCacheKey();
$cached = $this->cache->load($cacheKey, $variableCacheKey);
if (is_array($cached)) {
$cached = $this->mapStubFilenames($cached, fn (string $filename): ?string => $this->resolveStubFilename($filename));
}
if (is_array($cached)) {
if ($identifier->isConstant()) {
return ReflectionConstant::importFromCache($reflector, $cached);
}
if ($identifier->isFunction()) {
return ReflectionFunction::importFromCache($reflector, $cached);
}
if ($identifier->isClass()) {
if (array_key_exists('backingType', $cached)) {
return ReflectionEnum::importFromCache($reflector, $cached);
}
return ReflectionClass::importFromCache($reflector, $cached);
}
}
$reflection = $this->inner->locateIdentifier($reflector, $identifier);
if (
$reflection instanceof ReflectionClass
|| $reflection instanceof ReflectionFunction
|| $reflection instanceof ReflectionConstant
) {
$exported = $this->mapStubFilenames($reflection->exportToCache(), fn (string $filename): ?string => $this->relativizeStubFilename($filename));
if ($exported !== null) {
$this->cache->save($cacheKey, $variableCacheKey, $exported);
}
}
return $reflection;
}
/**
* Maps the stub path of every located source in the exported blob: the
* reflection's own, and the ones that the methods an enum gets from the
* engine (cases(), from(), tryFrom()) carry next to it.
*
* @param array<string, mixed> $data
* @param callable(string): ?string $mapFilename
* @return array<string, mixed>|null null when any of the paths cannot be mapped
*/
private function mapStubFilenames(array $data, callable $mapFilename): ?array
{
$locatedSource = $this->mapStubFilename($data['locatedSource'] ?? null, $mapFilename);
if ($locatedSource === null) {
return null;
}
$data['locatedSource'] = $locatedSource;
foreach ($data['immediateMethods'] ?? [] as $i => $method) {
if (!isset($method['locatedSource'])) {
continue;
}
$locatedSource = $this->mapStubFilename($method['locatedSource'], $mapFilename);
if ($locatedSource === null) {
return null;
}
$data['immediateMethods'][$i]['locatedSource'] = $locatedSource;
}
return $data;
}
/**
* @param callable(string): ?string $mapFilename
* @return array<string, mixed>|null
*/
private function mapStubFilename(mixed $locatedSource, callable $mapFilename): ?array
{
$filename = $locatedSource['data']['filename'] ?? null;
if (!is_string($filename)) {
return null;
}
$filename = $mapFilename($filename);
if ($filename === null) {
return null;
}
$locatedSource['data']['filename'] = $filename;
return $locatedSource;
}
private function relativizeStubFilename(string $filename): ?string
{
$markerPosition = strpos($filename, self::STUBS_DIR_MARKER);
if ($markerPosition === false) {
return null;
}
return self::RELATIVE_FILENAME_PREFIX . substr($filename, $markerPosition + strlen(self::STUBS_DIR_MARKER));
}
private function resolveStubFilename(string $filename): ?string
{
if (!str_starts_with($filename, self::RELATIVE_FILENAME_PREFIX)) {
return null;
}
$resolved = ($this->stubsRootDir ??= ComposerHelper::getPhpStormStubsDir()) . '/' . substr($filename, strlen(self::RELATIVE_FILENAME_PREFIX));
if (!is_file($resolved)) {
return null;
}
return $resolved;
}
/**
* @return list<Reflection>
*/
#[Override]
public function locateIdentifiersByType(Reflector $reflector, IdentifierType $identifierType): array
{
return $this->inner->locateIdentifiersByType($reflector, $identifierType);
}
private function getVariableCacheKey(): string
{
return $this->variableCacheKey ??= sprintf(
'v4-%s-%s-%s-%s',
ComposerHelper::getBetterReflectionVersion(),
ComposerHelper::getPhpStormStubsVersion(),
$this->phpVersion->getVersionString(),
$this->extensionVersionProvider->getCacheKey(),
);
}
}