99use PhpParser \Node \Name \FullyQualified ;
1010use PhpParser \Node \Stmt \GroupUse ;
1111use PhpParser \Node \Stmt \Use_ ;
12+ use PHPStan \Analyser \Scope ;
1213use Rector \CodingStyle \ClassNameImport \ClassNameImportSkipper ;
1314use Rector \Naming \Naming \AliasNameResolver ;
1415use Rector \NodeTypeResolver \Node \AttributeKey ;
@@ -90,6 +91,12 @@ private function importNameAndCollectNewUseStatement(
9091 return $ nameInUse ;
9192 }
9293
94+ $ nameInNamespacedScope = $ this ->resolveNameInNamespacedScope ($ fullyQualified );
95+ if ($ nameInNamespacedScope instanceof Name) {
96+ $ nameInNamespacedScope ->setAttribute (AttributeKey::NAMESPACED_NAME , $ fullyQualified ->toString ());
97+ return $ nameInNamespacedScope ;
98+ }
99+
93100 // the same end is already imported → skip
94101 if ($ this ->classNameImportSkipper ->shouldSkipNameForFullyQualifiedObjectType (
95102 $ file ,
@@ -111,6 +118,34 @@ private function importNameAndCollectNewUseStatement(
111118 return $ fullyQualifiedObjectType ->getShortNameNode ();
112119 }
113120
121+ private function resolveNameInNamespacedScope (FullyQualified $ fullyQualified ): ?Name
122+ {
123+ /**
124+ * Note: Don't use ScopeFetcher::fetch() on Name instance,
125+ * Scope can be null on Name
126+ * This is part of ScopeAnalyzer::NON_REFRESHABLE_NODES
127+ * @see https://github.com/rectorphp/rector-src/blob/9929af7c0179929b4fde6915cb7a06c3141dde6c/src/NodeAnalyzer/ScopeAnalyzer.php#L17
128+ */
129+ $ scope = $ fullyQualified ->getAttribute (AttributeKey::SCOPE );
130+ if (! $ scope instanceof Scope) {
131+ return null ;
132+ }
133+
134+ $ namespace = $ scope ->getNamespace ();
135+ if ($ namespace === null ) {
136+ return null ;
137+ }
138+
139+ $ shortName = $ fullyQualified ->getLast ();
140+ $ namepaceFullyQualifiedName = substr ($ fullyQualified ->toString (), 0 , -strlen ($ shortName ) - 1 );
141+
142+ if ($ namepaceFullyQualifiedName === $ namespace ) {
143+ return new Name ($ shortName );
144+ }
145+
146+ return null ;
147+ }
148+
114149 private function addUseImport (
115150 File $ file ,
116151 FullyQualified $ fullyQualified ,
0 commit comments