Repository navigation
Expand file tree
/
Copy pathClassLikeHandler.php
More file actions
236 lines (213 loc) · 9.83 KB
/
Copy pathClassLikeHandler.php
File metadata and controls
236 lines (213 loc) · 9.83 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
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\StmtHandler;
use PhpParser\Node;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\Trait_;
use PHPStan\Analyser\AttributesHandler;
use PHPStan\Analyser\CalledMethodProcessor;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\InternalStatementResult;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\StatementContext;
use PHPStan\Analyser\StmtHandler;
use PHPStan\BetterReflection\Reflection\Adapter\ReflectionClass;
use PHPStan\BetterReflection\Reflection\ReflectionEnum;
use PHPStan\BetterReflection\Reflector\Reflector;
use PHPStan\BetterReflection\SourceLocator\Ast\Strategy\NodeToReflection;
use PHPStan\BetterReflection\SourceLocator\Located\LocatedSource;
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredExtensions;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\DependencyInjection\ExtensionsCollection;
use PHPStan\File\FileReader;
use PHPStan\Node\ClassConstantsNode;
use PHPStan\Node\ClassMethodsNode;
use PHPStan\Node\ClassPropertiesNode;
use PHPStan\Node\ClassStatementsGatherer;
use PHPStan\Node\InClassNode;
use PHPStan\PhpDoc\PhpDocPrivateClassConstFetchFinder;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ClassReflectionFactory;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Properties\ReadWritePropertiesExtension;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
use function array_values;
use function sprintf;
use function usort;
use const PHP_VERSION_ID;
/**
* Trait_ has its own handler; every other ClassLike subtype lands here.
*
* @implements StmtHandler<ClassLike>
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/ClassLikeHandler.cpp')]
final class ClassLikeHandler implements StmtHandler
{
/**
* @param ExtensionsCollection<ReadWritePropertiesExtension> $readWritePropertiesExtensions
*/
public function __construct(
private Reflector $reflector,
private ClassReflectionFactory $classReflectionFactory,
private CalledMethodProcessor $calledMethodProcessor,
private ReflectionProvider $reflectionProvider,
private AttributesHandler $attributesHandler,
#[AutowiredExtensions(of: ReadWritePropertiesExtension::class)]
private ExtensionsCollection $readWritePropertiesExtensions,
private PhpDocPrivateClassConstFetchFinder $phpDocPrivateClassConstFetchFinder,
)
{
}
public function supports(Stmt $stmt): bool
{
return $stmt instanceof ClassLike && !$stmt instanceof Trait_;
}
public function processStmt(
NodeScopeResolver $nodeScopeResolver,
Stmt $stmt,
MutatingScope $scope,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
): InternalStatementResult
{
$declarationDependencies = $this->getDeclarationDependencies($scope, $stmt);
// declaring a class/interface/enum defines it in global state,
// so a matching negative existence-check narrowing must be forgotten
if ($stmt instanceof Node\Stmt\Interface_) {
$existenceCheckFunctionNames = ['interface_exists'];
} elseif ($stmt instanceof Node\Stmt\Enum_) {
$existenceCheckFunctionNames = ['class_exists', 'enum_exists'];
} else {
$existenceCheckFunctionNames = ['class_exists'];
}
$name = $stmt->namespacedName ?? $stmt->name;
$scope = $scope->invalidateExistenceCheckExpressions($existenceCheckFunctionNames, $name instanceof Name ? $name->toString() : null);
if (!$context->isTopLevel()) {
return new InternalStatementResult($scope, hasYield: false, isAlwaysTerminating: false, exitPoints: [], throwPoints: [], impurePoints: [], dependencies: $declarationDependencies);
}
if (isset($stmt->namespacedName)) {
$classReflection = $this->getCurrentClassReflection($stmt, $stmt->namespacedName->toString(), $scope);
$classScope = $scope->enterClass($classReflection);
} elseif ($stmt instanceof Class_) {
if ($stmt->name === null) {
throw new ShouldNotHappenException();
}
if (!$stmt->isAnonymous()) {
$classReflection = $this->reflectionProvider->getClass($stmt->name->toString());
} else {
$classReflection = $this->reflectionProvider->getAnonymousClassReflection($stmt, $scope);
}
$classScope = $scope->enterClass($classReflection);
} else {
throw new ShouldNotHappenException();
}
$classStatementsGatherer = new ClassStatementsGatherer($this->phpDocPrivateClassConstFetchFinder, $classReflection, $nodeCallback);
// the class attributes are processed before the InClassNode emission, so
// rules firing on it (ClassAttributesRule) read the attribute arguments
// from the storage
$attributesDependencies = $this->attributesHandler->processAttributeGroups($nodeScopeResolver, $stmt, $stmt->attrGroups, $classScope, $storage, $classStatementsGatherer);
$nodeScopeResolver->callNodeCallback($nodeCallback, new InClassNode($stmt, $classReflection), $classScope, $storage);
$classLikeStatements = $stmt->stmts;
// analyze static methods first; constructor next; instance methods and property hooks last so we can carry over the scope
usort($classLikeStatements, static function ($a, $b) {
if ($a instanceof Node\Stmt\Property) {
return 1;
}
if ($b instanceof Node\Stmt\Property) {
return -1;
}
if (!$a instanceof Node\Stmt\ClassMethod || !$b instanceof Node\Stmt\ClassMethod) {
return 0;
}
return [!$a->isStatic(), $a->name->toLowerString() !== '__construct'] <=> [!$b->isStatic(), $b->name->toLowerString() !== '__construct'];
});
// Class members have their own inference context, including when the class
// declaration is visited during an enclosing body's observation pass.
$bodyResult = $nodeScopeResolver->processStmtNodesInternal($stmt, $classLikeStatements, $classScope, $storage, $classStatementsGatherer, StatementContext::createTopLevel());
$nodeScopeResolver->callNodeCallback($nodeCallback, new ClassPropertiesNode($stmt, $this->readWritePropertiesExtensions, $classStatementsGatherer->getProperties(), $classStatementsGatherer->getPropertyUsages(), $classStatementsGatherer->getMethodCalls(), $classStatementsGatherer->getReturnStatementsNodes(), $classStatementsGatherer->getPropertyAssigns(), $classReflection), $classScope, $storage);
$nodeScopeResolver->callNodeCallback($nodeCallback, new ClassMethodsNode($stmt, $classStatementsGatherer->getMethods(), $classStatementsGatherer->getMethodCalls(), $classReflection), $classScope, $storage);
$nodeScopeResolver->callNodeCallback($nodeCallback, new ClassConstantsNode($stmt, $classStatementsGatherer->getConstants(), $classStatementsGatherer->getConstantFetches(), $classReflection), $classScope, $storage);
$classReflection->evictPrivateSymbols();
$this->calledMethodProcessor->clearCalledMethodResults();
return new InternalStatementResult($scope, hasYield: false, isAlwaysTerminating: false, exitPoints: [], throwPoints: [], impurePoints: [], dependencies: Dependencies::merge(
$declarationDependencies,
$attributesDependencies,
// the code of a trait is analysed as a part of every class using it
Dependencies::create($classScope->getFile(), usedTraits: array_values($classReflection->getTraits(true))),
$bodyResult->getDependencies(),
));
}
/**
* The class itself and what it extends and implements.
*/
private function getDeclarationDependencies(MutatingScope $scope, ClassLike $stmt): ?Dependencies
{
$classNames = [];
if (isset($stmt->namespacedName)) {
$classNames[] = $stmt->namespacedName->toString();
}
if ($stmt instanceof Class_) {
if ($stmt->extends !== null) {
$classNames[] = $stmt->extends->toString();
}
foreach ($stmt->implements as $className) {
$classNames[] = $className->toString();
}
} elseif ($stmt instanceof Node\Stmt\Interface_) {
foreach ($stmt->extends as $className) {
$classNames[] = $className->toString();
}
} elseif ($stmt instanceof Node\Stmt\Enum_) {
foreach ($stmt->implements as $className) {
$classNames[] = $className->toString();
}
}
return Dependencies::create($scope->getFile(), classNames: $classNames);
}
private function getCurrentClassReflection(Node\Stmt\ClassLike $stmt, string $className, Scope $scope): ClassReflection
{
if (!$this->reflectionProvider->hasClass($className)) {
return $this->createAstClassReflection($stmt, $className, $scope);
}
$defaultClassReflection = $this->reflectionProvider->getClass($className);
if ($defaultClassReflection->getFileName() !== $scope->getFile()) {
return $this->createAstClassReflection($stmt, $className, $scope);
}
$startLine = $defaultClassReflection->getNativeReflection()->getStartLine();
if ($startLine !== $stmt->getStartLine()) {
return $this->createAstClassReflection($stmt, $className, $scope);
}
return $defaultClassReflection;
}
private function createAstClassReflection(Node\Stmt\ClassLike $stmt, string $className, Scope $scope): ClassReflection
{
$nodeToReflection = new NodeToReflection();
$betterReflectionClass = $nodeToReflection->__invoke(
$this->reflector,
$stmt,
new LocatedSource(FileReader::read($scope->getFile()), $className, $scope->getFile()),
$scope->getNamespace() !== null ? new Node\Stmt\Namespace_(new Name($scope->getNamespace())) : null,
);
if (!$betterReflectionClass instanceof \PHPStan\BetterReflection\Reflection\ReflectionClass) {
throw new ShouldNotHappenException();
}
return $this->classReflectionFactory->create(
$betterReflectionClass->getName(),
$betterReflectionClass instanceof ReflectionEnum && PHP_VERSION_ID >= 80000
? new \PHPStan\BetterReflection\Reflection\Adapter\ReflectionEnum($betterReflectionClass)
: new ReflectionClass($betterReflectionClass),
null,
null,
null,
sprintf('%s:%d', $scope->getFile(), $stmt->getStartLine()),
);
}
}