Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PostRector] Keep first comment before first Use_ if removed on UnusedImportRemovingPostRector #6522

Merged
merged 1 commit into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/PostRector/Rector/UnusedImportRemovingPostRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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]);
}
}
}

Expand Down
25 changes: 25 additions & 0 deletions tests/Issues/NoNamespaced/Fixture/keep_first_comment.php.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

/**
* @license some license docblock
*/
use PhpParser\Node\Scalar\String_ as Foo;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Stmt\Expression as Bar;

new Bar(new Array_([]));

?>
-----
<?php

/**
* @license some license docblock
*/

use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Stmt\Expression as Bar;

new Bar(new Array_([]));

?>