Repository navigation
Expand file tree
/
Copy pathPropertyFetchHandler.php
More file actions
244 lines (221 loc) · 10.6 KB
/
Copy pathPropertyFetchHandler.php
File metadata and controls
244 lines (221 loc) · 10.6 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\Analyser\ExprHandler;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Identifier;
use PhpParser\Node\Stmt;
use PHPStan\Analyser\ExpressionContext;
use PHPStan\Analyser\ExpressionResult;
use PHPStan\Analyser\ExpressionResultFactory;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\ExprHandler;
use PHPStan\Analyser\ExprHandler\Helper\DefaultNarrowingHelper;
use PHPStan\Analyser\InternalThrowPoint;
use PHPStan\Analyser\IssetabilityDescriptor;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\PropertyHookThrowPointsResolver;
use PHPStan\Analyser\SpecifiedTypes;
use PHPStan\Analyser\TypeSpecifierContext;
use PHPStan\Analyser\VariableFlow;
use PHPStan\Analyser\VariableFlowBuilder;
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Php\PhpVersion;
use PHPStan\Rules\Properties\FoundPropertyReflection;
use PHPStan\Rules\Properties\PropertyReflectionFinder;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\ErrorType;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function array_map;
use function array_merge;
use function count;
/**
* @implements ExprHandler<PropertyFetch>
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/PropertyFetchHandler.cpp')]
final class PropertyFetchHandler implements ExprHandler
{
public function __construct(
private PhpVersion $phpVersion,
private PropertyReflectionFinder $propertyReflectionFinder,
private ExpressionResultFactory $expressionResultFactory,
private PropertyHookThrowPointsResolver $propertyHookThrowPointsResolver,
private DefaultNarrowingHelper $defaultNarrowingHelper,
)
{
}
public function supports(Expr $expr): bool
{
return $expr instanceof PropertyFetch;
}
public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Expr $expr, MutatingScope $scope, ExpressionResultStorage $storage, callable $nodeCallback, ExpressionContext $context): ExpressionResult
{
$beforeScope = $scope;
$scopeBeforeVar = $scope;
$varResult = $nodeScopeResolver->processExprNode($stmt, $expr->var, $scope, $storage, $nodeCallback, $context->enterDeep());
$nameResult = null;
if (!$expr->name instanceof Identifier) {
$nameResult = $nodeScopeResolver->processExprNode($stmt, $expr->name, $varResult->getScope(), $storage, $nodeCallback, $context->enterDeep());
}
return $this->composeResult($nodeScopeResolver, $expr, $varResult, $nameResult, $scopeBeforeVar, $beforeScope);
}
/**
* Builds the property read's ExpressionResult from the already-walked
* receiver and name results - the fetch is not re-walked. processExpr()
* routes through this; AssignHandler::prepareTarget() calls it to price a
* read-modify-write target from the write walk's child results.
*/
public function composeResult(NodeScopeResolver $nodeScopeResolver, PropertyFetch $expr, ExpressionResult $varResult, ?ExpressionResult $nameResult, MutatingScope $scopeBeforeVar, MutatingScope $beforeScope): ExpressionResult
{
$hasYield = $varResult->hasYield();
$throwPoints = $varResult->getThrowPoints();
$impurePoints = $varResult->getImpurePoints();
$isAlwaysTerminating = $varResult->isAlwaysTerminating();
$scope = $varResult->getScope();
$mayShortCircuit = false;
if ($expr->name instanceof Identifier) {
if ($this->phpVersion->supportsPropertyHooks()) {
$propertyName = $expr->name->toString();
$propertyHolderType = $varResult->getType();
$propertyReflection = $scopeBeforeVar->getInstancePropertyReflection($propertyHolderType, $propertyName);
if ($propertyReflection !== null) {
$propertyDeclaringClass = $propertyReflection->getDeclaringClass();
if ($propertyDeclaringClass->hasNativeProperty($propertyName)) {
$nativeProperty = $propertyDeclaringClass->getNativeProperty($propertyName);
$throwPoints = array_merge($throwPoints, $this->propertyHookThrowPointsResolver->getThrowPointsFromPropertyHook($scopeBeforeVar, $expr, $nativeProperty, 'get'));
$impurePoints = array_merge($impurePoints, $nodeScopeResolver->getImpurePointsFromPropertyHook($scopeBeforeVar, $expr, $nativeProperty, 'get'));
}
}
}
} elseif ($nameResult !== null) {
// a fetch that is a link in a nullsafe chain may never run - see
// MethodCallHandler::processExpr(). Only the dynamic name is skipped
// with it, so an Identifier name never has to resolve the receiver type.
$mayShortCircuit = $varResult->containsNullsafe() && TypeCombinator::containsNull($varResult->getType());
$hasYield = $hasYield || $nameResult->hasYield();
$throwPoints = array_merge($throwPoints, $nameResult->getThrowPoints());
$impurePoints = array_merge($impurePoints, $nameResult->getImpurePoints());
$isAlwaysTerminating = $isAlwaysTerminating || (!$mayShortCircuit && $nameResult->isAlwaysTerminating());
$scope = $nameResult->getScope();
if ($mayShortCircuit) {
// the dynamic name expression was not evaluated in the
// short-circuited world
$scope = $scope->mergeWith($varResult->getScope());
}
if ($this->phpVersion->supportsPropertyHooks()) {
$throwPoints[] = InternalThrowPoint::createImplicit($scope, $expr);
}
}
$result = $this->expressionResultFactory->create(
$scope,
beforeScope: $beforeScope,
expr: $expr,
variableFlow: VariableFlow::sequence(
$varResult->getVariableFlow(),
$nameResult !== null && $mayShortCircuit
? VariableFlow::choice($nameResult->getVariableFlow(), null)
: ($nameResult !== null ? $nameResult->getVariableFlow() : null),
VariableFlowBuilder::throws($expr, $throwPoints),
),
hasYield: $hasYield,
isAlwaysTerminating: $isAlwaysTerminating,
throwPoints: $throwPoints,
impurePoints: $impurePoints,
containsNullsafe: $varResult->containsNullsafe(),
issetabilityDescriptor: IssetabilityDescriptor::property($varResult, fn (MutatingScope $s): ?FoundPropertyReflection => $this->propertyReflectionFinder->findPropertyReflectionFromNode($expr, $s), $expr),
typeCallback: function (bool $nativeTypesPromoted) use ($expr, $varResult, $nameResult, $beforeScope): Type {
// a fetch on a nullsafe chain whose receiver is currently nullable
// short-circuits to null - the receiver result carries whether the
// chain contains a ?-> (a plain nullable receiver does not propagate)
$receiverType = $nativeTypesPromoted ? $varResult->getNativeType() : $varResult->getType();
$shortCircuit = static fn (Type $type): Type => $varResult->containsNullsafe() && TypeCombinator::containsNull($receiverType)
? TypeCombinator::addNull($type)
: $type;
// the property's class/visibility/assign context is lexical, so it
// comes from beforeScope; the scope-dependent receiver type is read
// from the operand result above.
$reflectionScope = $nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope;
$resolveProperty = function (string $propertyName) use ($nativeTypesPromoted, $reflectionScope, $receiverType, $varResult, $expr): Type {
if ($nativeTypesPromoted) {
// unlike getInstancePropertyReflection(), do not pick only the union
// members that have the property - a fetch on e.g. a null member
// does not produce the property's native type
$nativeReceiverType = $varResult->containsNullsafe() ? TypeCombinator::removeNull($receiverType) : $receiverType;
if (!$nativeReceiverType->hasInstanceProperty($propertyName)->yes()) {
return new ErrorType();
}
$propertyReflection = $reflectionScope->getInstancePropertyReflection($nativeReceiverType, $propertyName);
if ($propertyReflection === null) {
return new ErrorType();
}
if (!$propertyReflection->hasNativeType()) {
return new MixedType();
}
return $propertyReflection->getNativeType();
}
return $this->propertyFetchType($reflectionScope, $receiverType, $propertyName, $expr) ?? new ErrorType();
};
if ($expr->name instanceof Identifier) {
return $shortCircuit($resolveProperty($expr->name->toString()));
}
// dynamic property fetch $obj->$name: resolve each possible name
// from beforeScope. The asking scope is not narrowed per name, so
// $obj->{'foo'}-style fetches can be less precise. Every caller
// walks a non-Identifier name and passes its result.
if ($nameResult === null) {
throw new ShouldNotHappenException();
}
$nameType = $nativeTypesPromoted ? $nameResult->getNativeType() : $nameResult->getType();
if (count($nameType->getConstantStrings()) > 0) {
return TypeCombinator::union(
...array_map(static function ($constantString) use ($resolveProperty): Type {
if ($constantString->getValue() === '') {
return new ErrorType();
}
return $resolveProperty($constantString->getValue());
}, $nameType->getConstantStrings()),
);
}
return new MixedType();
},
specifyTypesCallback: fn (TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes => $this->defaultNarrowingHelper->specifyDefaultTypesWithNullsafeFan($expr, $context, $beforeScope, $nativeTypesPromoted),
);
return $result->withDependencies(Dependencies::merge(
$varResult->getDependencies(),
$nameResult !== null ? $nameResult->getDependencies() : null,
$this->getDependencies($scopeBeforeVar, $expr, $varResult, $result),
));
}
/**
* The classes of the object the property is fetched from, the class declaring it, and the classes
* in its type.
*/
private function getDependencies(MutatingScope $scope, PropertyFetch $expr, ExpressionResult $varResult, ExpressionResult $result): ?Dependencies
{
$fetchedOnType = $varResult->getType();
$classNames = [];
if ($expr->name instanceof Identifier) {
$propertyReflection = $scope->getInstancePropertyReflection($fetchedOnType, $expr->name->toString());
if ($propertyReflection !== null) {
$classNames[] = $propertyReflection->getDeclaringClass()->getName();
}
}
return Dependencies::create($scope->getFile(), [$fetchedOnType, $result->getType()], $classNames);
}
private function propertyFetchType(MutatingScope $scope, Type $fetchedOnType, string $propertyName, PropertyFetch $propertyFetch): ?Type
{
$propertyReflection = $scope->getInstancePropertyReflection($fetchedOnType, $propertyName);
if ($propertyReflection === null) {
return null;
}
if ($scope->isInWriteExpressionAssign($propertyFetch)) {
return $propertyReflection->getWritableType();
}
return $propertyReflection->getReadableType();
}
}