From 3e2261082485c99798f84248b8c686becca10af3 Mon Sep 17 00:00:00 2001 From: Mark Date: Tue, 3 Mar 2026 17:57:57 +0100 Subject: [PATCH] fix extractor erasing comments when they precede strict_types --- src/PhpGenerator/Extractor.php | 25 +++++++++++++------ .../Extractor.extractAll.file.comments.phpt | 13 ++++++++++ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/PhpGenerator/Extractor.php b/src/PhpGenerator/Extractor.php index 19013082..eb369ee3 100644 --- a/src/PhpGenerator/Extractor.php +++ b/src/PhpGenerator/Extractor.php @@ -243,18 +243,29 @@ public function extractAll(): PhpFile { $phpFile = new PhpFile; + $comments = []; + $firstStmt = $this->statements[0] ?? null; + if ($firstStmt instanceof Node\Stmt\Declare_) { + $comments = $firstStmt->getComments(); + if (!$firstStmt->getDocComment()) { + $comments = []; + $firstStmt = $this->statements[1] ?? null; + } + } + if ( - ($firstStmt = $this->statements[0] ?? null) - && ($firstStmt = $firstStmt instanceof Node\Stmt\Declare_ ? $this->statements[1] ?? null : $firstStmt) + !$comments + && $firstStmt && !$firstStmt instanceof Node\Stmt\ClassLike && !$firstStmt instanceof Node\Stmt\Function_ ) { $comments = $firstStmt->getComments(); - foreach ($comments as $i => $comment) { - if ($comment instanceof PhpParser\Comment\Doc) { - $phpFile->setComment(Helpers::unformatDocComment($comment->getReformattedText())); - break; - } + } + + foreach ($comments as $comment) { + if ($comment instanceof PhpParser\Comment\Doc) { + $phpFile->setComment(Helpers::unformatDocComment($comment->getReformattedText())); + break; } } diff --git a/tests/PhpGenerator/Extractor.extractAll.file.comments.phpt b/tests/PhpGenerator/Extractor.extractAll.file.comments.phpt index ee0b1827..810ecc8a 100644 --- a/tests/PhpGenerator/Extractor.extractAll.file.comments.phpt +++ b/tests/PhpGenerator/Extractor.extractAll.file.comments.phpt @@ -30,6 +30,19 @@ $file = (new Extractor(<<<'XX' Assert::same('doc comment', $file->getComment()); +$file = (new Extractor(<<<'XX' + extractAll(); + +Assert::same('doc comment', $file->getComment()); + + $file = (new Extractor(<<<'XX'