55namespace Rector \Application ;
66
77use Nette \Utils \FileSystem ;
8+ use PhpParser \NodeTraverser ;
9+ use PhpParser \NodeVisitor \NameResolver ;
810use PHPStan \AnalysedCodeException ;
911use PHPStan \Parser \ParserErrorsException ;
1012use Rector \Caching \Detector \ChangedFilesDetector ;
@@ -63,20 +65,13 @@ public function processFile(File $file, Configuration $configuration): FileProce
6365 // 1. change nodes with Rector Rules
6466 $ newStmts = $ this ->rectorNodeTraverser ->traverse ($ file ->getNewStmts ());
6567
66- // 2. refresh used imports on the FileNode from current stmts,
67- // so post rectors read them without re-traversing, yet stay in sync each iteration
68- $ fileNode = $ newStmts [0 ] ?? null ;
69- if ($ fileNode instanceof FileNode) {
70- $ fileNode ->setUsedImports ($ this ->usedImportsResolver ->resolveForStmts ($ fileNode ->stmts ));
71- }
72-
73- // 3. apply post rectors
68+ // 2. apply post rectors
7469 $ postNewStmts = $ this ->postFileProcessor ->traverse ($ newStmts , $ file );
7570
76- // 4 . this is needed for new tokens added in "afterTraverse()"
71+ // 3 . this is needed for new tokens added in "afterTraverse()"
7772 $ file ->changeNewStmts ($ postNewStmts );
7873
79- // 5 . print to file or string
74+ // 4 . print to file or string
8075 // important to detect if file has changed
8176 $ this ->printFile ($ file , $ configuration , $ filePath );
8277
@@ -88,7 +83,7 @@ public function processFile(File $file, Configuration $configuration): FileProce
8883 $ fileHasChanged = true ;
8984 } while (true );
9085
91- // 6 . add as cacheable if not changed at all
86+ // 5 . add as cacheable if not changed at all
9287 if (! $ fileHasChanged ) {
9388 $ this ->changedFilesDetector ->addCacheableFile ($ filePath );
9489 } else {
@@ -179,8 +174,16 @@ private function parseFileNodes(File $file, bool $forNewestSupportedVersion = tr
179174
180175 $ oldStmts = $ stmtsAndTokens ->getStmts ();
181176
182- // wrap in FileNode to allow file-level rules
183- $ oldStmts = [new FileNode ($ oldStmts )];
177+ // resolve names up front, so used imports (incl. the class FQN) are resolvable at construction,
178+ // before scope decoration runs; only annotates namespacedName, does not replace name nodes
179+ $ nameResolvingTraverser = new NodeTraverser (new NameResolver (null , [
180+ 'preserveOriginalNames ' => true ,
181+ 'replaceNodes ' => false ,
182+ ]));
183+ $ nameResolvingTraverser ->traverse ($ oldStmts );
184+
185+ // wrap in FileNode to allow file-level rules; seed used imports once, kept in sync incrementally
186+ $ oldStmts = [new FileNode ($ oldStmts , $ this ->usedImportsResolver ->resolveForStmts ($ oldStmts ))];
184187
185188 $ oldTokens = $ stmtsAndTokens ->getTokens ();
186189
0 commit comments