1 | <?php |
||
38 | final class UseStmtCollection implements IteratorAggregate |
||
39 | { |
||
40 | /** |
||
41 | * @var Use_[][] |
||
42 | */ |
||
43 | private $nodes = [ |
||
44 | null => [], |
||
45 | ]; |
||
46 | |||
47 | public function add(?Name $namespaceName, Use_ $node): void |
||
48 | { |
||
49 | $this->nodes[(string) $namespaceName][] = clone_node($node); |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * Finds the statements matching the given name. |
||
54 | * |
||
55 | * $name = 'Foo'; |
||
56 | * |
||
57 | * use X; |
||
58 | * use Bar\Foo; |
||
59 | * use Y; |
||
60 | * |
||
61 | * will return the use statement for `Bar\Foo`. |
||
62 | * |
||
63 | * @param Name|null $namespaceName |
||
64 | * @param Name $node |
||
65 | * |
||
66 | * @return null|Name |
||
67 | */ |
||
68 | 7 | public function findStatementForNode(?Name $namespaceName, Name $node): ?Name |
|
69 | { |
||
70 | 7 | $name = strtolower($node->getFirst()); |
|
71 | |||
72 | 7 | $parentNode = ParentNodeAppender::findParent($node); |
|
73 | |||
74 | 7 | if ($parentNode instanceof ClassLike |
|
75 | 7 | && $node instanceof NamedIdentifier |
|
76 | 7 | && $node->getOriginalNode() === $parentNode->name |
|
77 | ) { |
||
78 | // The current node can either be the class like name or one of its elements, e.g. extends or implements. |
||
79 | // In the first case, the node was original an Identifier. |
||
80 | |||
81 | return null; |
||
82 | } |
||
83 | |||
84 | 7 | $useStatements = $this->nodes[(string) $namespaceName] ?? []; |
|
85 | |||
86 | 7 | foreach ($useStatements as $use_) { |
|
87 | foreach ($use_->uses as $useStatement) { |
||
88 | if (!($useStatement instanceof UseUse)) { |
||
89 | continue; |
||
90 | } |
||
91 | |||
92 | if ($name === $useStatement->getAlias()->toLowerString()) { |
||
93 | if ($this->isFunctionName($node, $parentNode)) { |
||
94 | if (Use_::TYPE_FUNCTION === $use_->type) { |
||
95 | return $useStatement->name; |
||
96 | } |
||
97 | |||
98 | continue; |
||
99 | } |
||
100 | |||
101 | if ($parentNode instanceof ConstFetch && 1 === count($node->parts)) { |
||
102 | if (Use_::TYPE_CONSTANT === $use_->type) { |
||
103 | return $useStatement->name; |
||
104 | } |
||
105 | |||
106 | continue; |
||
107 | } |
||
108 | |||
109 | // Match the alias |
||
110 | return $useStatement->name; |
||
111 | } |
||
112 | |||
113 | if (null !== $useStatement->alias) { |
||
114 | continue; |
||
115 | } |
||
116 | } |
||
117 | } |
||
118 | |||
119 | 7 | return null; |
|
120 | } |
||
121 | |||
122 | /** |
||
123 | * @inheritdoc |
||
124 | */ |
||
125 | public function getIterator(): iterable |
||
129 | |||
130 | private function isFunctionName(Name $node, ?Node $parentNode): bool |
||
147 | } |
||
148 |