Repository navigation
Expand file tree
/
Copy pathUnusedImportRemovingPostRector.php
More file actions
310 lines (252 loc) · 9.68 KB
/
Copy pathUnusedImportRemovingPostRector.php
File metadata and controls
310 lines (252 loc) · 9.68 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
<?php
declare(strict_types=1);
namespace Rector\PostRector\Rector;
use Nette\Utils\Strings;
use PhpParser\Comment;
use PhpParser\Comment\Doc;
use PhpParser\Node;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\Declare_;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Node\Stmt\Nop;
use PhpParser\Node\Stmt\Use_;
use PhpParser\Node\UseItem;
use PhpParser\NodeVisitor;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PhpDocParser\NodeTraverser\SimpleCallableNodeTraverser;
use Rector\PhpParser\Node\FileNode;
use Rector\ValueObject\Application\File;
final class UnusedImportRemovingPostRector extends AbstractPostRector
{
private ?File $usedNamesFile = null;
/**
* @var array<int, array{version: int, names: string[]}>
*/
private array $usedNamesCache = [];
public function __construct(
private readonly SimpleCallableNodeTraverser $simpleCallableNodeTraverser,
private readonly PhpDocInfoFactory $phpDocInfoFactory,
) {
}
public function enterNode(Node $node): ?Node
{
if (! $node instanceof Namespace_ && ! $node instanceof FileNode) {
return null;
}
// no use import at this level → nothing to remove, skip the full name resolution walks
if (! $this->hasUseStmt($node->stmts)) {
return null;
}
$hasChanged = false;
$namespaceOriginalCase = $node instanceof Namespace_ && $node->name instanceof Name
? $node->name->toString()
: null;
$namesInOriginalCase = $this->resolveUsedPhpAndDocNames($node);
$namesInLowerCase = array_map(strtolower(...), $namesInOriginalCase);
$firstStmtKey = 0;
foreach ($node->stmts as $key => $stmt) {
if ($stmt instanceof Declare_ && $key === 0) {
++$firstStmtKey;
}
if (! $stmt instanceof Use_) {
continue;
}
if ($stmt->uses === [] || $namesInOriginalCase === []) {
unset($node->stmts[$key]);
$hasChanged = true;
continue;
}
$isCaseSensitive = $stmt->type === Use_::TYPE_CONSTANT;
$names = $isCaseSensitive ? $namesInOriginalCase : $namesInLowerCase;
$namespaceName = $namespaceOriginalCase === null
? null
: ($isCaseSensitive
? $namespaceOriginalCase
: strtolower($namespaceOriginalCase));
foreach ($stmt->uses as $useUseKey => $useUse) {
if ($this->isUseImportUsed($useUse, $isCaseSensitive, $names, $namespaceName)) {
continue;
}
unset($stmt->uses[$useUseKey]);
$hasChanged = true;
}
if ($stmt->uses === []) {
$comments = $node->stmts[$key]->getComments();
if ($key === $firstStmtKey && $comments !== []) {
$node->stmts[$key] = new Nop();
$node->stmts[$key]->setAttribute(AttributeKey::COMMENTS, $comments);
} else {
unset($node->stmts[$key]);
}
}
}
if ($hasChanged === false) {
return null;
}
$this->addRectorClassWithLine($node);
$node->stmts = array_values($node->stmts);
return $node;
}
/**
* @param Node[] $stmts
*/
private function hasUseStmt(array $stmts): bool
{
return array_any($stmts, fn(Node $stmt): bool => $stmt instanceof Use_);
}
/**
* Single walk that collects both the referenced PHP names and the docblock class names,
* so the file stmts are traversed once instead of twice.
*
* @return string[]
*/
private function findUsedNames(Namespace_|FileNode $rootNode): array
{
// the root node's own docblock (the former doc walk traversed the root node, not just its stmts)
$names = $this->resolveDocBlockNames($rootNode);
$this->simpleCallableNodeTraverser->traverseNodesWithCallable($rootNode->stmts, function (Node $node) use (
&$names
): int|null {
// collect the node's docblock first, so a Use_ node's own doc is still read before we stop descending
$names = [...$names, ...$this->resolveDocBlockNames($node)];
if ($node instanceof Use_) {
return NodeVisitor::DONT_TRAVERSE_CURRENT_AND_CHILDREN;
}
if (! $node instanceof Name) {
return null;
}
if ($node instanceof FullyQualified) {
$originalName = $node->getAttribute(AttributeKey::ORIGINAL_NAME);
if ($originalName instanceof Name) {
// collect original Name as cover namespaced used
$names[] = $originalName->toString();
return null;
}
}
$names[] = $node->toString();
return null;
});
return $names;
}
/**
* @return string[]
*/
private function resolveDocBlockNames(Node $node): array
{
$comments = $node->getComments();
if ($comments === []) {
return [];
}
$docs = array_filter($comments, static fn (Comment $comment): bool => $comment instanceof Doc);
if ($docs === []) {
return [];
}
$names = [];
$totalDocs = count($docs);
foreach ($docs as $doc) {
$nodeToCheck = $totalDocs === 1 ? $node : clone $node;
if ($totalDocs > 1) {
$nodeToCheck->setDocComment($doc);
}
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($nodeToCheck);
$names = [...$names, ...$phpDocInfo->getAnnotationClassNames()];
$constFetchNodeNames = $phpDocInfo->getConstFetchNodeClassNames();
$names = [...$names, ...$constFetchNodeNames];
$genericTagClassNames = $phpDocInfo->getGenericTagClassNames();
$names = [...$names, ...$genericTagClassNames];
$inlineGenericUsesTagClassNames = $phpDocInfo->getInlineGenericUsesTagClassNames();
$names = [...$names, ...$inlineGenericUsesTagClassNames];
$arrayItemTagClassNames = $phpDocInfo->getArrayItemNodeClassNames();
$names = [...$names, ...$arrayItemTagClassNames];
}
return $names;
}
/**
* @return string[]
*/
private function resolveUsedPhpAndDocNames(Namespace_|FileNode $rootNode): array
{
// the referenced names only change with a new stmts version, while the post-rector chain
// re-runs this node across convergence iterations, so cache per (file, version)
$file = $this->getFile();
if ($file !== $this->usedNamesFile) {
$this->usedNamesFile = $file;
$this->usedNamesCache = [];
}
$version = $file->getNewStmtsVersion();
$objectId = spl_object_id($rootNode);
$cached = $this->usedNamesCache[$objectId] ?? null;
if ($cached !== null && $cached['version'] === $version) {
return $cached['names'];
}
$names = array_unique($this->findUsedNames($rootNode));
$this->usedNamesCache[$objectId] = [
'version' => $version,
'names' => $names,
];
return $names;
}
/**
* @param string[] $names
*/
private function isUseImportUsed(
UseItem $useItem,
bool $isCaseSensitive,
array $names,
?string $namespaceName
): bool {
$comparedName = $useItem->alias instanceof Identifier
? $useItem->alias->toString()
: $useItem->name->toString();
if (! $isCaseSensitive) {
$comparedName = strtolower($comparedName);
}
if (in_array($comparedName, $names, true)) {
return true;
}
$lastName = Strings::after($comparedName, '\\', -1);
$namespacedPrefix = $lastName . '\\';
if ($namespacedPrefix === '\\') {
$namespacedPrefix = $comparedName . '\\';
}
// match partial import
foreach ($names as $name) {
if (str_starts_with($name, '\\')) {
continue;
}
if ($this->isSubNamespace($name, $comparedName, $namespacedPrefix)) {
return true;
}
if (! str_starts_with($name, $lastName . '\\')) {
if (str_starts_with($name, $comparedName . '\\')) {
return true;
}
continue;
}
if ($namespaceName === null) {
return true;
}
if (! str_starts_with($name, $namespaceName . '\\')) {
return true;
}
}
return false;
}
private function isSubNamespace(string $name, string $comparedName, string $namespacedPrefix): bool
{
// a partially qualified name like "Foo\Bar" resolves through the import of its first
// segment, never through an import whose tail it happens to match, so only a single
// segment name (the imported short name) may be matched against the import's tail here
if (! str_contains($name, '\\') && str_ends_with($comparedName, '\\' . $name)) {
return true;
}
if (str_starts_with($name, $namespacedPrefix)) {
$subNamespace = substr($name, strlen($namespacedPrefix));
return ! str_contains($subNamespace, '\\');
}
return false;
}
}