Skip to content

Commit b28538d

Browse files
authored
[PostRector] Keep first comment after declare(strict_types=1) on UnusedImportRemovingPostRector (#7042)
1 parent 186c22e commit b28538d

2 files changed

Lines changed: 47 additions & 1 deletion

File tree

src/PostRector/Rector/UnusedImportRemovingPostRector.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use PhpParser\Node\Identifier;
1212
use PhpParser\Node\Name;
1313
use PhpParser\Node\Name\FullyQualified;
14+
use PhpParser\Node\Stmt\Declare_;
1415
use PhpParser\Node\Stmt\Namespace_;
1516
use PhpParser\Node\Stmt\Nop;
1617
use PhpParser\Node\Stmt\Use_;
@@ -42,7 +43,12 @@ public function enterNode(Node $node): ?Node
4243
$namesInOriginalCase = $this->resolveUsedPhpAndDocNames($node);
4344
$namesInLowerCase = array_map(strtolower(...), $namesInOriginalCase);
4445

46+
$firstStmtKey = 0;
4547
foreach ($node->stmts as $key => $stmt) {
48+
if ($stmt instanceof Declare_ && $key === 0) {
49+
$firstStmtKey += 1;
50+
}
51+
4652
if (! $stmt instanceof Use_) {
4753
continue;
4854
}
@@ -74,7 +80,7 @@ public function enterNode(Node $node): ?Node
7480
if ($stmt->uses === []) {
7581
$comments = $node->stmts[$key]->getComments();
7682

77-
if ($key === 0 && $comments !== []) {
83+
if ($key === $firstStmtKey && $comments !== []) {
7884
$node->stmts[$key] = new Nop();
7985
$node->stmts[$key]->setAttribute(AttributeKey::COMMENTS, $comments);
8086
} else {
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
// some comment about the file
6+
// not about the use statement below it.
7+
/* comment
8+
block */
9+
######
10+
11+
use Exception;
12+
use stdClass;
13+
use SomeOtherClass;
14+
15+
final class KeepFirstCommentAfterDeclare
16+
{
17+
public ?stdClass $b;
18+
}
19+
20+
?>
21+
-----
22+
<?php
23+
24+
declare(strict_types=1);
25+
26+
// some comment about the file
27+
// not about the use statement below it.
28+
/* comment
29+
block */
30+
######
31+
32+
33+
use stdClass;
34+
35+
final class KeepFirstCommentAfterDeclare
36+
{
37+
public ?stdClass $b;
38+
}
39+
40+
?>

0 commit comments

Comments
 (0)