Repository navigation
Expand file tree
/
Copy pathTraitUseHandler.php
More file actions
259 lines (232 loc) · 9.06 KB
/
Copy pathTraitUseHandler.php
File metadata and controls
259 lines (232 loc) · 9.06 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\StmtHandler;
use PhpParser\Modifiers;
use PhpParser\Node;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\TraitUse;
use PHPStan\Analyser\AttributesHandler;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\InternalStatementResult;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\NoopNodeCallback;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\StatementContext;
use PHPStan\Analyser\StmtHandler;
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\File\FileHelper;
use PHPStan\Node\InTraitNode;
use PHPStan\Parser\Parser;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\ShouldNotHappenException;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\FileTypeMapper;
use function array_key_exists;
use function is_array;
use function strtolower;
/**
* @implements StmtHandler<TraitUse>
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/TraitUseHandler.cpp')]
final class TraitUseHandler implements StmtHandler
{
/**
* Names of traits whose statements are currently being processed, keyed by lowercased name.
*
* @var array<string, true>
*/
private array $currentlyProcessedTraits = [];
public function __construct(
private ReflectionProvider $reflectionProvider,
private FileHelper $fileHelper,
#[AutowiredParameter(ref: '@defaultAnalysisParser')]
private Parser $parser,
private AttributesHandler $attributesHandler,
private FileTypeMapper $fileTypeMapper,
)
{
}
public function supports(Stmt $stmt): bool
{
return $stmt instanceof TraitUse;
}
public function processStmt(
NodeScopeResolver $nodeScopeResolver,
Stmt $stmt,
MutatingScope $scope,
ExpressionResultStorage $storage,
callable $nodeCallback,
StatementContext $context,
): InternalStatementResult
{
// fresh storage - the same trait node objects are processed once per
// using class must not see results from a previous pass
$traitStorage = new ExpressionResultStorage();
$scope->pushExpressionResultStorage($traitStorage);
try {
$traitDependencies = $this->processTraitUse($nodeScopeResolver, $stmt, $scope, $traitStorage, $nodeCallback);
} finally {
$scope->popExpressionResultStorage();
}
// class-level node callbacks (like ClassMethodsNode) are invoked with
// the outer storage but ask about expressions inside the used trait
$storage->mergeResults($traitStorage);
return new InternalStatementResult($scope, hasYield: false, isAlwaysTerminating: false, exitPoints: [], throwPoints: [], impurePoints: [], dependencies: Dependencies::merge($this->getDependencies($scope, $stmt), $traitDependencies));
}
/**
* The used traits and the classes the @use tags reference.
*/
private function getDependencies(MutatingScope $scope, Node\Stmt\TraitUse $stmt): ?Dependencies
{
$classNames = [];
foreach ($stmt->traits as $traitName) {
$classNames[] = $traitName->toString();
}
$types = [];
$docComment = $stmt->getDocComment();
if ($docComment !== null) {
$usesTags = $this->fileTypeMapper->getResolvedPhpDoc(
$scope->getFile(),
$scope->isInClass() ? $scope->getClassReflection()->getName() : null,
$scope->isInTrait() ? $scope->getTraitReflection()->getName() : null,
null,
$docComment->getText(),
)->getUsesTags();
foreach ($usesTags as $usesTag) {
$types[] = $usesTag->getType();
}
}
return Dependencies::create($scope->getFile(), $types, $classNames);
}
/**
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
private function processTraitUse(NodeScopeResolver $nodeScopeResolver, Node\Stmt\TraitUse $node, MutatingScope $classScope, ExpressionResultStorage $storage, callable $nodeCallback): ?Dependencies
{
// inside a trait, only the traits reflection says it uses are processed: a trait on a
// trait cycle uses none, so its members stay those reflection knows about
$usedTraitNames = null;
if ($classScope->isInTrait()) {
$usedTraitNames = [];
foreach ($classScope->getTraitReflection()->getTraits() as $usedTrait) {
$usedTraitNames[strtolower($usedTrait->getName())] = true;
}
}
$dependencies = [];
foreach ($node->traits as $trait) {
$traitName = (string) $trait;
if ($usedTraitNames !== null && !array_key_exists(strtolower($traitName), $usedTraitNames)) {
continue;
}
// traits can use each other in a cycle (even use themselves) which is a runtime
// fatal error in PHP, but must not send the analyser into an endless recursion
if (array_key_exists(strtolower($traitName), $this->currentlyProcessedTraits)) {
continue;
}
if (!$this->reflectionProvider->hasClass($traitName)) {
continue;
}
$traitReflection = $this->reflectionProvider->getClass($traitName);
$traitFileName = $traitReflection->getFileName();
if ($traitFileName === null) {
continue; // trait from eval or from PHP itself
}
$fileName = $this->fileHelper->normalizePath($traitFileName);
if (!$nodeScopeResolver->isAnalysedFile($fileName)) {
continue;
}
$adaptations = [];
foreach ($node->adaptations as $adaptation) {
if ($adaptation->trait === null) {
$adaptations[] = $adaptation;
continue;
}
if ($adaptation->trait->toLowerString() !== $trait->toLowerString()) {
continue;
}
$adaptations[] = $adaptation;
}
$parserNodes = $this->parser->parseFile($fileName);
$this->currentlyProcessedTraits[strtolower($traitName)] = true;
try {
$this->processNodesForTraitUse($nodeScopeResolver, $parserNodes, $traitReflection, $classScope, $storage, $adaptations, $nodeCallback, $dependencies);
} finally {
unset($this->currentlyProcessedTraits[strtolower($traitName)]);
}
}
return Dependencies::merge(...$dependencies);
}
/**
* @param Node[]|Node|scalar|null $node
* @param Node\Stmt\TraitUseAdaptation[] $adaptations
* @param callable(Node $node, Scope $scope): void $nodeCallback
* @param list<Dependencies|null> $dependencies what the walked trait statements depend on
*/
private function processNodesForTraitUse(NodeScopeResolver $nodeScopeResolver, $node, ClassReflection $traitReflection, MutatingScope $scope, ExpressionResultStorage $storage, array $adaptations, callable $nodeCallback, array &$dependencies): void
{
if ($node instanceof Node) {
if ($node instanceof Node\Stmt\Trait_ && $traitReflection->getName() === (string) $node->namespacedName && $traitReflection->getNativeReflection()->getStartLine() === $node->getStartLine()) {
$methodModifiers = [];
$methodNames = [];
foreach ($adaptations as $adaptation) {
if (!$adaptation instanceof Node\Stmt\TraitUseAdaptation\Alias) {
continue;
}
$methodName = $adaptation->method->toLowerString();
if ($adaptation->newModifier !== null) {
$methodModifiers[$methodName] = $adaptation->newModifier;
}
if ($adaptation->newName === null) {
continue;
}
$methodNames[$methodName] = $adaptation->newName;
}
$stmts = $node->stmts;
foreach ($stmts as $i => $stmt) {
if (!$stmt instanceof Node\Stmt\ClassMethod) {
continue;
}
$methodName = $stmt->name->toLowerString();
$methodAst = clone $stmt;
$stmts[$i] = $methodAst;
if (array_key_exists($methodName, $methodModifiers)) {
$methodAst->flags = ($methodAst->flags & ~ Modifiers::VISIBILITY_MASK) | $methodModifiers[$methodName];
}
if (!array_key_exists($methodName, $methodNames)) {
continue;
}
$methodAst->setAttribute('originalTraitMethodName', $methodAst->name->toLowerString());
$methodAst->name = $methodNames[$methodName];
}
if (!$scope->isInClass()) {
throw new ShouldNotHappenException();
}
$traitScope = $scope->enterTrait($traitReflection);
// attribute args are not processed as part of the trait statements
// but rules like TraitAttributesRule ask about their types
$this->attributesHandler->processAttributeGroups($nodeScopeResolver, $node, $node->attrGroups, $traitScope, $storage, new NoopNodeCallback());
$nodeScopeResolver->callNodeCallback($nodeCallback, new InTraitNode($node, $traitReflection, $scope->getClassReflection()), $traitScope, $storage);
$dependencies[] = $nodeScopeResolver->processStmtNodesInternal($node, $stmts, $traitScope, $storage, $nodeCallback, StatementContext::createTopLevel())->getDependencies();
return;
}
if ($node instanceof Node\Stmt\ClassLike) {
return;
}
if ($node instanceof Node\FunctionLike) {
return;
}
foreach ($node->getSubNodeNames() as $subNodeName) {
$subNode = $node->{$subNodeName};
$this->processNodesForTraitUse($nodeScopeResolver, $subNode, $traitReflection, $scope, $storage, $adaptations, $nodeCallback, $dependencies);
}
} elseif (is_array($node)) {
foreach ($node as $subNode) {
$this->processNodesForTraitUse($nodeScopeResolver, $subNode, $traitReflection, $scope, $storage, $adaptations, $nodeCallback, $dependencies);
}
}
}
}