1313use Rector \Contract \PhpParser \Node \StmtsAwareInterface ;
1414use Rector \Contract \Rector \HTMLAverseRectorInterface ;
1515use Rector \PhpParser \Node \BetterNodeFinder ;
16+ use Rector \PhpParser \Node \CustomNode \FileWithoutNamespace ;
1617use Rector \PHPUnit \NodeAnalyzer \TestsNodeAnalyzer ;
1718use Rector \Rector \AbstractRector ;
1819use Rector \TypeDeclaration \NodeAnalyzer \DeclareStrictTypeFinder ;
@@ -83,7 +84,16 @@ public function beforeTraverse(array $nodes): ?array
8384
8485 // when first stmt is Declare_, verify if there is strict_types definition already,
8586 // as multiple declare is allowed, with declare(strict_types=1) only allowed on very first stmt
86- if ($ this ->declareStrictTypeFinder ->hasDeclareStrictTypes ($ rootStmt )) {
87+ if ($ rootStmt instanceof FileWithoutNamespace) {
88+ $ currentNode = current ($ rootStmt ->stmts );
89+ if (! $ currentNode instanceof Stmt) {
90+ return null ;
91+ }
92+
93+ if ($ this ->declareStrictTypeFinder ->hasDeclareStrictTypes ($ currentNode )) {
94+ return null ;
95+ }
96+ } elseif ($ this ->declareStrictTypeFinder ->hasDeclareStrictTypes ($ rootStmt )) {
8797 return null ;
8898 }
8999
@@ -94,6 +104,15 @@ public function beforeTraverse(array $nodes): ?array
94104 $ rectorWithLineChange = new RectorWithLineChange (self ::class, $ rootStmt ->getStartLine ());
95105 $ this ->file ->addRectorClassWithLine ($ rectorWithLineChange );
96106
107+ if ($ rootStmt instanceof FileWithoutNamespace) {
108+ $ stmts = [$ this ->nodeFactory ->createDeclaresStrictType ()];
109+ $ stmts = array_merge ($ stmts , [new Nop ()]);
110+ $ stmts = array_merge ($ stmts , $ rootStmt ->stmts );
111+ $ rootStmt ->stmts = $ stmts ;
112+
113+ return [$ rootStmt ];
114+ }
115+
97116 return [$ this ->nodeFactory ->createDeclaresStrictType (), new Nop (), ...$ nodes ];
98117 }
99118
0 commit comments