Skip to content

Commit d2f0b01

Browse files
committed
Extractor: supports file comment extraction with singleline declare
1 parent 52aff4d commit d2f0b01

2 files changed

Lines changed: 32 additions & 5 deletions

File tree

src/PhpGenerator/Extractor.php

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -238,12 +238,28 @@ public function extractAll(): PhpFile
238238
{
239239
$phpFile = new PhpFile;
240240

241+
$firstStmt = $this->statements[0] ?? null;
241242
if (
242-
$this->statements
243-
&& !$this->statements[0] instanceof Node\Stmt\ClassLike
244-
&& !$this->statements[0] instanceof Node\Stmt\Function_
243+
$firstStmt instanceof Node\Stmt\Declare_
244+
&& $firstStmt->declares[0]->key->name === 'strict_types'
245245
) {
246-
$this->addCommentAndAttributes($phpFile, $this->statements[0]);
246+
$firstStmt = $this->statements[1] ?? null;
247+
}
248+
249+
if (
250+
$firstStmt
251+
&& !$firstStmt instanceof Node\Stmt\ClassLike
252+
&& !$firstStmt instanceof Node\Stmt\Function_
253+
) {
254+
$comments = $firstStmt->getComments();
255+
foreach ($comments as $i => $comment) {
256+
if ($comment instanceof PhpParser\Comment\Doc) {
257+
$phpFile->setComment(Helpers::unformatDocComment($comment->getReformattedText()));
258+
unset($comments[$i]);
259+
$firstStmt->setAttribute('comments', array_values($comments));
260+
break;
261+
}
262+
}
247263
}
248264

249265
$namespaces = ['' => $this->statements];
@@ -439,7 +455,7 @@ private function addFunctionToFile(PhpFile $phpFile, Node\Stmt\Function_ $node):
439455

440456

441457
private function addCommentAndAttributes(
442-
PhpFile|ClassLike|Constant|Property|GlobalFunction|Method|Parameter|EnumCase|TraitUse|PropertyHook $element,
458+
ClassLike|Constant|Property|GlobalFunction|Method|Parameter|EnumCase|TraitUse|PropertyHook $element,
443459
Node $node,
444460
): void
445461
{

tests/PhpGenerator/Extractor.extractAll.file.comments.phpt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,17 @@ Assert::null($file->getComment());
2121
Assert::same('doc comment', $file->getClasses()['Class1']->getComment());
2222

2323

24+
$file = (new Extractor(<<<'XX'
25+
<?php declare(strict_types=1);
26+
27+
/** doc comment */
28+
29+
namespace Abc;
30+
XX))->extractAll();
31+
32+
Assert::same('doc comment', $file->getComment());
33+
34+
2435
$file = (new Extractor(<<<'XX'
2536
<?php
2637

0 commit comments

Comments
 (0)