diff --git a/src/PostRector/Rector/UnusedImportRemovingPostRector.php b/src/PostRector/Rector/UnusedImportRemovingPostRector.php index e6b50887354..4d172a590c8 100644 --- a/src/PostRector/Rector/UnusedImportRemovingPostRector.php +++ b/src/PostRector/Rector/UnusedImportRemovingPostRector.php @@ -12,6 +12,7 @@ use PhpParser\Node\Name; use PhpParser\Node\Name\FullyQualified; use PhpParser\Node\Stmt\Namespace_; +use PhpParser\Node\Stmt\Nop; use PhpParser\Node\Stmt\Use_; use PhpParser\Node\UseItem; use PhpParser\NodeVisitor; @@ -71,7 +72,14 @@ public function enterNode(Node $node): ?Node } if ($stmt->uses === []) { - unset($node->stmts[$key]); + $comments = $node->stmts[$key]->getComments(); + + if ($key === 0 && $comments !== []) { + $node->stmts[$key] = new Nop(); + $node->stmts[$key]->setAttribute(AttributeKey::COMMENTS, $comments); + } else { + unset($node->stmts[$key]); + } } } diff --git a/tests/Issues/NoNamespaced/Fixture/keep_first_comment.php.inc b/tests/Issues/NoNamespaced/Fixture/keep_first_comment.php.inc new file mode 100644 index 00000000000..58b3fe666e1 --- /dev/null +++ b/tests/Issues/NoNamespaced/Fixture/keep_first_comment.php.inc @@ -0,0 +1,25 @@ + +----- +