Repository navigation
Expand file tree
/
Copy pathFileNode.php
More file actions
452 lines (377 loc) · 14.1 KB
/
Copy pathFileNode.php
File metadata and controls
452 lines (377 loc) · 14.1 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
<?php
declare(strict_types=1);
namespace Rector\PhpParser\Node;
use PhpParser\Node;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Declare_;
use PhpParser\Node\Stmt\GroupUse;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Node\Stmt\Nop;
use PhpParser\Node\Stmt\Use_;
use Rector\CodingStyle\ClassNameImport\ValueObject\PendingImports;
use Rector\CodingStyle\ClassNameImport\ValueObject\UsedImports;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\StaticTypeMapper\ValueObject\Type\AliasedObjectType;
use Rector\StaticTypeMapper\ValueObject\Type\FullyQualifiedObjectType;
/**
* Inspired by https://github.com/phpstan/phpstan-src/commit/ed81c3ad0b9877e6122c79b4afda9d10f3994092
*/
final class FileNode extends Stmt
{
/**
* Imports queued to be added on the next UseAddingPostRector run; scoped to this file
*/
private readonly PendingImports $pendingImports;
/**
* @param Stmt[] $stmts
* @param UsedImports $usedImports Resolved once on file parse, then kept in sync incrementally as imports are added
*/
public function __construct(
public array $stmts,
private UsedImports $usedImports,
) {
$this->pendingImports = new PendingImports();
$firstStmt = $stmts[0] ?? null;
$attributes = $firstStmt instanceof Node ? $firstStmt->getAttributes() : [];
parent::__construct($attributes);
}
/**
* Adds new use imports into the file/namespace and keeps the tracked used imports in sync,
* so the next traversal iteration converges without re-resolving.
*
* @param array<FullyQualifiedObjectType|AliasedObjectType> $useImportTypes
* @param FullyQualifiedObjectType[] $constantUseImportTypes
* @param FullyQualifiedObjectType[] $functionUseImportTypes
*/
public function addImports(
array $useImportTypes,
array $constantUseImportTypes,
array $functionUseImportTypes
): bool {
$namespace = $this->resolvePlacementNamespace();
$placementNode = $namespace ?? $this;
$namespaceName = $namespace instanceof Namespace_ && $namespace->name instanceof Name
? $namespace->name->toString()
: null;
// no namespace? only keep namespaced names at the file top
if (! $namespace instanceof Namespace_) {
$useImportTypes = $this->filterOutNonNamespacedNames($useImportTypes);
}
$useImportTypes = $this->diffFullyQualifiedObjectTypes($useImportTypes, $this->usedImports->getUseImports());
$constantUseImportTypes = $this->diffFullyQualifiedObjectTypes(
$constantUseImportTypes,
$this->usedImports->getConstantImports()
);
$functionUseImportTypes = $this->diffFullyQualifiedObjectTypes(
$functionUseImportTypes,
$this->usedImports->getFunctionImports()
);
$newUses = $this->createUses($useImportTypes, $constantUseImportTypes, $functionUseImportTypes, $namespaceName);
if ($newUses === []) {
return false;
}
// remove empty use stmts
$placementNode->stmts = array_values(array_filter($placementNode->stmts, static function (Stmt $stmt): bool {
if (! $stmt instanceof Use_) {
return true;
}
return $stmt->uses !== [];
}));
// place after declare strict_types
foreach ($placementNode->stmts as $key => $stmt) {
// maybe just added a space
if ($stmt instanceof Nop) {
continue;
}
// when we found a non-declare, directly stop
if (! $stmt instanceof Declare_) {
break;
}
$nodesToAdd = array_merge([new Nop()], $newUses);
$this->mirrorUseComments($placementNode->stmts, $newUses, $key + 1);
// remove space before next use tweak
$nextStmt = $placementNode->stmts[$key + 1] ?? null;
if ($nextStmt instanceof Use_ || $nextStmt instanceof GroupUse) {
$nextStmt->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
array_splice($placementNode->stmts, $key + 1, 0, $nodesToAdd);
$this->appendUsedImports($useImportTypes, $functionUseImportTypes, $constantUseImportTypes);
return true;
}
$this->mirrorUseComments($placementNode->stmts, $newUses);
// make use stmts first
$placementNode->stmts = array_merge($newUses, $this->resolveInsertNop($placementNode), $placementNode->stmts);
$placementNode->stmts = array_values($placementNode->stmts);
$this->appendUsedImports($useImportTypes, $functionUseImportTypes, $constantUseImportTypes);
return true;
}
public function getPendingImports(): PendingImports
{
return $this->pendingImports;
}
public function hasImport(FullyQualifiedObjectType $fullyQualifiedObjectType): bool
{
return array_any(
$this->resolveUsedImportTypes(),
fn (AliasedObjectType|FullyQualifiedObjectType $useImport): bool => $useImport->equals(
$fullyQualifiedObjectType
)
);
}
/**
* The queued use imports merged with the use imports already present in the file
*
* @return array<AliasedObjectType|FullyQualifiedObjectType>
*/
public function resolveUsedImportTypes(): array
{
$objectTypes = $this->pendingImports->getUseImports();
foreach ($this->getUsesAndGroupUses() as $use) {
$prefix = $use instanceof GroupUse ? $use->prefix . '\\' : '';
foreach ($use->uses as $useUse) {
if ($useUse->alias instanceof Identifier) {
$objectTypes[] = new AliasedObjectType($useUse->alias->toString(), $prefix . $useUse->name);
} else {
$objectTypes[] = new FullyQualifiedObjectType($prefix . $useUse->name);
}
}
}
return $objectTypes;
}
/**
* Removes the given use imports from the file/namespace
*
* @param string[] $removedUses
*/
public function removeImports(array $removedUses): bool
{
$node = $this->resolvePlacementNamespace() ?? $this;
$hasRemoved = false;
foreach ($node->stmts as $key => $stmt) {
if (! $stmt instanceof Use_) {
continue;
}
if ($this->removeUseFromUse($removedUses, $stmt)) {
$hasRemoved = true;
}
// remove empty uses
if ($stmt->uses === []) {
unset($node->stmts[$key]);
}
}
if ($hasRemoved) {
$node->stmts = array_values($node->stmts);
}
return $hasRemoved;
}
/**
* This triggers Printed method with "pFileNode" name
* @see \Rector\PhpParser\Printer\BetterStandardPrinter::pStmt_FileNode()
*/
public function getType(): string
{
return 'Stmt_FileNode';
}
/**
* @return array<int, string>
*/
public function getSubNodeNames(): array
{
return ['stmts'];
}
public function isNamespaced(): bool
{
return array_any($this->stmts, fn (Stmt $stmt): bool => $stmt instanceof Namespace_);
}
public function getNamespace(): ?Namespace_
{
/** @var Namespace_[] $namespaces */
$namespaces = array_filter($this->stmts, static fn (Stmt $stmt): bool => $stmt instanceof Namespace_);
if (count($namespaces) === 1) {
return current($namespaces);
}
return null;
}
/**
* @return array<Use_|GroupUse>
*/
public function getUsesAndGroupUses(): array
{
$rootNode = $this->getNamespace();
if (! $rootNode instanceof Namespace_) {
$rootNode = $this;
}
return array_filter(
$rootNode->stmts,
static fn (Stmt $stmt): bool => $stmt instanceof Use_ || $stmt instanceof GroupUse
);
}
/**
* @return Use_[]
*/
public function getUses(): array
{
$rootNode = $this->getNamespace();
if (! $rootNode instanceof Namespace_) {
$rootNode = $this;
}
return array_filter($rootNode->stmts, static fn (Stmt $stmt): bool => $stmt instanceof Use_);
}
/**
* Mirrors the legacy placement target: the first namespace if any, else the file root itself
*/
private function resolvePlacementNamespace(): ?Namespace_
{
foreach ($this->stmts as $stmt) {
if ($stmt instanceof Namespace_) {
return $stmt;
}
}
return null;
}
/**
* @param array<FullyQualifiedObjectType|AliasedObjectType> $useImportTypes
* @return array<FullyQualifiedObjectType|AliasedObjectType>
*/
private function filterOutNonNamespacedNames(array $useImportTypes): array
{
$namespacedUseImportTypes = [];
foreach ($useImportTypes as $useImportType) {
if (! str_contains($useImportType->getClassName(), '\\')) {
continue;
}
$namespacedUseImportTypes[] = $useImportType;
}
return $namespacedUseImportTypes;
}
/**
* @param array<FullyQualifiedObjectType|AliasedObjectType> $useImportTypes
* @param FullyQualifiedObjectType[] $functionUseImportTypes
* @param FullyQualifiedObjectType[] $constantUseImportTypes
*/
private function appendUsedImports(
array $useImportTypes,
array $functionUseImportTypes,
array $constantUseImportTypes
): void {
$this->usedImports = new UsedImports(
array_merge($this->usedImports->getUseImports(), $useImportTypes),
array_merge($this->usedImports->getFunctionImports(), $functionUseImportTypes),
array_merge($this->usedImports->getConstantImports(), $constantUseImportTypes),
);
}
/**
* @template TObjectType of FullyQualifiedObjectType|AliasedObjectType
* @param array<TObjectType> $mainTypes
* @param array<FullyQualifiedObjectType|AliasedObjectType> $typesToRemove
* @return list<TObjectType>
*/
private function diffFullyQualifiedObjectTypes(array $mainTypes, array $typesToRemove): array
{
foreach ($mainTypes as $key => $mainType) {
foreach ($typesToRemove as $typeToRemove) {
if ($mainType->equals($typeToRemove)) {
unset($mainTypes[$key]);
}
}
}
return array_values($mainTypes);
}
/**
* @param array<AliasedObjectType|FullyQualifiedObjectType> $useImportTypes
* @param array<FullyQualifiedObjectType|AliasedObjectType> $constantUseImportTypes
* @param array<FullyQualifiedObjectType|AliasedObjectType> $functionUseImportTypes
* @return Use_[]
*/
private function createUses(
array $useImportTypes,
array $constantUseImportTypes,
array $functionUseImportTypes,
?string $namespaceName
): array {
$newUses = [];
/** @var array<Use_::TYPE_*, array<AliasedObjectType|FullyQualifiedObjectType>> $importsMapping */
$importsMapping = [
Use_::TYPE_NORMAL => $useImportTypes,
Use_::TYPE_CONSTANT => $constantUseImportTypes,
Use_::TYPE_FUNCTION => $functionUseImportTypes,
];
foreach ($importsMapping as $type => $importTypes) {
/** @var AliasedObjectType|FullyQualifiedObjectType $importType */
foreach ($importTypes as $importType) {
if ($namespaceName !== null && $this->isCurrentNamespace($namespaceName, $importType)) {
continue;
}
if ($namespaceName === null
&& $importType instanceof FullyQualifiedObjectType
&& substr_count(ltrim($importType->getClassName(), '\\'), '\\') === 0) {
continue;
}
$newUses[] = $importType->getUseNode($type);
}
}
return $newUses;
}
private function isCurrentNamespace(
string $namespaceName,
AliasedObjectType|FullyQualifiedObjectType $objectType
): bool {
$className = $objectType->getClassName();
if (! str_starts_with($className, $namespaceName . '\\')) {
return false;
}
return $namespaceName . '\\' . $objectType->getShortName() === $className;
}
/**
* @return Nop[]
*/
private function resolveInsertNop(self|Namespace_ $node): array
{
$currentStmt = $node->stmts[0] ?? null;
if (! $currentStmt instanceof Stmt || $currentStmt instanceof Use_ || $currentStmt instanceof GroupUse) {
return [];
}
return [new Nop()];
}
/**
* @param Stmt[] $stmts
* @param Use_[] $newUses
*/
private function mirrorUseComments(array $stmts, array $newUses, int $indexStmt = 0): void
{
if ($stmts === []) {
return;
}
if (isset($stmts[$indexStmt]) && $stmts[$indexStmt] instanceof Use_) {
$comments = (array) $stmts[$indexStmt]->getAttribute(AttributeKey::COMMENTS);
if ($comments !== []) {
$newUses[0]->setAttribute(
AttributeKey::COMMENTS,
$stmts[$indexStmt]->getAttribute(AttributeKey::COMMENTS)
);
$stmts[$indexStmt]->setAttribute(AttributeKey::COMMENTS, []);
}
}
}
/**
* @param string[] $removedUses
*/
private function removeUseFromUse(array $removedUses, Use_ $use): bool
{
$hasChanged = false;
foreach ($use->uses as $usesKey => $useUse) {
$useName = $useUse->name->toString();
if (! in_array($useName, $removedUses, true)) {
continue;
}
unset($use->uses[$usesKey]);
$hasChanged = true;
}
if ($hasChanged) {
$use->uses = array_values($use->uses);
}
return $hasChanged;
}
}