Repository navigation
Expand file tree
/
Copy pathAliasUsesResolver.php
More file actions
99 lines (80 loc) · 2.44 KB
/
Copy pathAliasUsesResolver.php
File metadata and controls
99 lines (80 loc) · 2.44 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
<?php
declare(strict_types=1);
namespace Rector\CodingStyle\ClassNameImport;
use PhpParser\Node\Identifier;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Node\Stmt\Use_;
use PhpParser\Node\UseItem;
use Rector\PhpParser\Node\FileNode;
use Rector\ValueObject\Application\File;
final class AliasUsesResolver
{
private ?File $cachedFile = null;
private int $cachedVersion = -1;
/**
* @var string[]
*/
private array $cachedAliasedUses = [];
public function __construct(
private readonly UseImportsTraverser $useImportsTraverser
) {
}
/**
* Aliased uses are file-global, so resolve once per file stmts version and reuse
* across every imported name in the same traversal
*
* @return string[]
*/
public function resolveFromFile(File $file): array
{
$newStmtsVersion = $file->getNewStmtsVersion();
if ($file === $this->cachedFile && $newStmtsVersion === $this->cachedVersion) {
return $this->cachedAliasedUses;
}
$this->cachedFile = $file;
$this->cachedVersion = $newStmtsVersion;
$this->cachedAliasedUses = $this->resolveFromNewStmts($file->getNewStmts());
return $this->cachedAliasedUses;
}
/**
* @param Stmt[] $stmts
* @return string[]
*/
public function resolveFromStmts(array $stmts): array
{
$aliasedUses = [];
/** @param Use_::TYPE_* $useType */
$this->useImportsTraverser->traverserStmts($stmts, static function (
int $useType,
UseItem $useItem,
string $name
) use (&$aliasedUses): void {
if ($useType !== Use_::TYPE_NORMAL) {
return;
}
if (! $useItem->alias instanceof Identifier) {
return;
}
$aliasedUses[] = $name;
});
return $aliasedUses;
}
/**
* @param Stmt[] $stmts
* @return string[]
*/
private function resolveFromNewStmts(array $stmts): array
{
/** @var Namespace_[]|FileNode[] $namespaces */
$namespaces = array_filter(
$stmts,
static fn (Stmt $stmt): bool => $stmt instanceof Namespace_ || $stmt instanceof FileNode
);
if (count($namespaces) !== 1) {
return [];
}
$namespace = current($namespaces);
return $this->resolveFromStmts($namespace->stmts);
}
}