forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNativeFunctionReflectionProvider.php
More file actions
244 lines (215 loc) · 8.84 KB
/
NativeFunctionReflectionProvider.php
File metadata and controls
244 lines (215 loc) · 8.84 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
<?php declare(strict_types = 1);
namespace PHPStan\Reflection\SignatureMap;
use PHPStan\BetterReflection\Identifier\Exception\InvalidIdentifierName;
use PHPStan\BetterReflection\Reflection\Adapter\ReflectionFunction;
use PHPStan\BetterReflection\Reflector\Exception\IdentifierNotFound;
use PHPStan\BetterReflection\Reflector\Reflector;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\PhpDoc\ResolvedPhpDocBlock;
use PHPStan\PhpDoc\StubPhpDocProvider;
use PHPStan\Reflection\Assertions;
use PHPStan\Reflection\AttributeReflection;
use PHPStan\Reflection\AttributeReflectionFactory;
use PHPStan\Reflection\ExtendedFunctionVariant;
use PHPStan\Reflection\InitializerExprContext;
use PHPStan\Reflection\Native\ExtendedNativeParameterReflection;
use PHPStan\Reflection\Native\NativeFunctionReflection;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\FileTypeMapper;
use PHPStan\Type\Generic\TemplateTypeMap;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use PHPStan\Type\TypehintHelper;
use function array_key_exists;
use function array_map;
use function is_string;
use function str_contains;
use function strtolower;
#[AutowiredService]
final class NativeFunctionReflectionProvider
{
/** @var NativeFunctionReflection[] */
private array $functionMap = [];
public function __construct(
private SignatureMapProvider $signatureMapProvider,
#[AutowiredParameter(ref: '@betterReflectionReflector')]
private Reflector $reflector,
private FileTypeMapper $fileTypeMapper,
private StubPhpDocProvider $stubPhpDocProvider,
private AttributeReflectionFactory $attributeReflectionFactory,
)
{
}
public function findFunctionReflection(string $functionName): ?NativeFunctionReflection
{
$lowerCasedFunctionName = strtolower($functionName);
$realFunctionName = $lowerCasedFunctionName;
if (isset($this->functionMap[$lowerCasedFunctionName])) {
return $this->functionMap[$lowerCasedFunctionName];
}
if (!$this->signatureMapProvider->hasFunctionSignature($lowerCasedFunctionName)) {
return null;
}
$throwType = null;
$reflectionFunctionAdapter = null;
$isDeprecated = false;
$phpDocReturnType = null;
$asserts = Assertions::createEmpty();
$docComment = null;
$returnsByReference = TrinaryLogic::createMaybe();
$acceptsNamedArguments = true;
$fileName = null;
$attributes = [];
try {
$reflectionFunction = $this->reflector->reflectFunction($functionName);
$reflectionFunctionAdapter = new ReflectionFunction($reflectionFunction);
$attributes = $reflectionFunctionAdapter->getAttributes();
$returnsByReference = TrinaryLogic::createFromBoolean($reflectionFunctionAdapter->returnsReference());
$realFunctionName = $reflectionFunction->getName();
$isDeprecated = $reflectionFunction->isDeprecated();
if ($reflectionFunction->getFileName() !== null) {
$fileName = $reflectionFunction->getFileName();
if (!$reflectionFunctionAdapter->isInternal() && !str_contains(strtolower($fileName), 'polyfill')) {
return null;
}
$docComment = $reflectionFunction->getDocComment();
if ($docComment !== null) {
$resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc($fileName, null, null, $reflectionFunction->getName(), $docComment);
$throwsTag = $resolvedPhpDoc->getThrowsTag();
if ($throwsTag !== null) {
$throwType = $throwsTag->getType();
}
}
}
} catch (IdentifierNotFound | InvalidIdentifierName) {
// pass
}
$functionSignaturesResult = $this->signatureMapProvider->getFunctionSignatures($lowerCasedFunctionName, null, $reflectionFunctionAdapter);
$phpDoc = $this->stubPhpDocProvider->findFunctionPhpDoc($lowerCasedFunctionName, array_map(static fn (ParameterSignature $parameter): string => $parameter->getName(), $functionSignaturesResult['positional'][0]->getParameters()));
if ($phpDoc !== null) {
if ($phpDoc->hasPhpDocString()) {
$docComment = $phpDoc->getPhpDocString();
}
if ($phpDoc->getThrowsTag() !== null) {
$throwType = $phpDoc->getThrowsTag()->getType();
}
$asserts = Assertions::createFromResolvedPhpDocBlock($phpDoc);
$phpDocReturnType = $this->getReturnTypeFromPhpDoc($phpDoc);
$acceptsNamedArguments = $phpDoc->acceptsNamedArguments();
}
$variantsByType = ['positional' => []];
foreach ($functionSignaturesResult as $signatureType => $functionSignatures) {
foreach ($functionSignatures ?? [] as $functionSignature) {
$variantsByType[$signatureType][] = new ExtendedFunctionVariant(
TemplateTypeMap::createEmpty(),
null,
array_map(static function (ParameterSignature $parameterSignature) use ($phpDoc): ExtendedNativeParameterReflection {
$type = $parameterSignature->getType();
$phpDocType = null;
$immediatelyInvokedCallable = TrinaryLogic::createMaybe();
$closureThisType = null;
if ($phpDoc !== null) {
if (array_key_exists($parameterSignature->getName(), $phpDoc->getParamTags())) {
$phpDocType = $phpDoc->getParamTags()[$parameterSignature->getName()]->getType();
}
if (array_key_exists($parameterSignature->getName(), $phpDoc->getParamsImmediatelyInvokedCallable())) {
$immediatelyInvokedCallable = TrinaryLogic::createFromBoolean($phpDoc->getParamsImmediatelyInvokedCallable()[$parameterSignature->getName()]);
}
if (array_key_exists($parameterSignature->getName(), $phpDoc->getParamClosureThisTags())) {
$closureThisType = $phpDoc->getParamClosureThisTags()[$parameterSignature->getName()]->getType();
}
}
return new ExtendedNativeParameterReflection(
$parameterSignature->getName(),
$parameterSignature->isOptional(),
TypehintHelper::decideType($type, $phpDocType),
$phpDocType ?? new MixedType(),
$type,
$parameterSignature->passedByReference(),
$parameterSignature->isVariadic(),
$parameterSignature->getDefaultValue(),
$phpDoc !== null ? NativeFunctionReflectionProvider::getParamOutTypeFromPhpDoc($parameterSignature->getName(), $phpDoc) : null,
$immediatelyInvokedCallable,
$closureThisType,
[],
);
}, $functionSignature->getParameters()),
$functionSignature->isVariadic(),
TypehintHelper::decideType($functionSignature->getReturnType(), $phpDocReturnType),
$phpDocReturnType ?? new MixedType(),
$functionSignature->getReturnType(),
);
}
}
if ($this->signatureMapProvider->hasFunctionMetadata($lowerCasedFunctionName)) {
$hasSideEffects = TrinaryLogic::createFromBoolean($this->signatureMapProvider->getFunctionMetadata($lowerCasedFunctionName)['hasSideEffects']);
} else {
$hasSideEffects = TrinaryLogic::createMaybe();
}
$phpstanAttributes = $this->attributeReflectionFactory->fromNativeReflection($attributes, InitializerExprContext::fromFunction($realFunctionName, $fileName));
if ($reflectionFunctionAdapter !== null) {
$phpstanAttributes = $this->addDeprecatedSinceAttribute($reflectionFunctionAdapter, $phpstanAttributes);
}
$functionReflection = new NativeFunctionReflection(
$realFunctionName,
$variantsByType['positional'],
$variantsByType['named'] ?? null,
$throwType,
$hasSideEffects,
$isDeprecated,
$asserts,
$docComment,
$returnsByReference,
$acceptsNamedArguments,
$phpstanAttributes,
);
$this->functionMap[$lowerCasedFunctionName] = $functionReflection;
return $functionReflection;
}
private function getReturnTypeFromPhpDoc(ResolvedPhpDocBlock $phpDoc): ?Type
{
$returnTag = $phpDoc->getReturnTag();
if ($returnTag === null) {
return null;
}
return $returnTag->getType();
}
private static function getParamOutTypeFromPhpDoc(string $paramName, ResolvedPhpDocBlock $stubPhpDoc): ?Type
{
$paramOutTags = $stubPhpDoc->getParamOutTags();
if (array_key_exists($paramName, $paramOutTags)) {
return $paramOutTags[$paramName]->getType();
}
return null;
}
/**
* @param list<AttributeReflection> $phpstanAttributes
* @return list<AttributeReflection>
*/
private function addDeprecatedSinceAttribute(ReflectionFunction $reflectionFunction, array $phpstanAttributes): array
{
foreach ($phpstanAttributes as $attr) {
if (strtolower($attr->getName()) === 'deprecated') {
return $phpstanAttributes;
}
}
foreach ($reflectionFunction->getAttributes() as $brAttr) {
if ($brAttr->getName() !== 'JetBrains\\PhpStorm\\Deprecated') {
continue;
}
$arguments = $brAttr->getArguments();
if (!isset($arguments['since']) || !is_string($arguments['since'])) {
continue;
}
$argTypes = ['since' => new ConstantStringType($arguments['since'])];
if (isset($arguments['message']) && is_string($arguments['message'])) {
$argTypes['message'] = new ConstantStringType($arguments['message']);
}
$phpstanAttributes[] = new AttributeReflection('Deprecated', $argTypes);
return $phpstanAttributes;
}
return $phpstanAttributes;
}
}