From 76270499da953e297dffecac5c246ea8d181d402 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Thu, 3 Sep 2026 17:27:30 +0700 Subject: [PATCH] [Php74] Keep comment inside If_ on IfToNullCoalescingAssignRector --- .../Fixture/keep_comment_inside_if.php.inc | 31 +++++++++++++++++++ .../If_/IfToNullCoalescingAssignRector.php | 7 +++-- 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 rules-tests/Php74/Rector/If_/IfToNullCoalescingAssignRector/Fixture/keep_comment_inside_if.php.inc diff --git a/rules-tests/Php74/Rector/If_/IfToNullCoalescingAssignRector/Fixture/keep_comment_inside_if.php.inc b/rules-tests/Php74/Rector/If_/IfToNullCoalescingAssignRector/Fixture/keep_comment_inside_if.php.inc new file mode 100644 index 00000000000..f609f9e41fd --- /dev/null +++ b/rules-tests/Php74/Rector/If_/IfToNullCoalescingAssignRector/Fixture/keep_comment_inside_if.php.inc @@ -0,0 +1,31 @@ + +----- + diff --git a/rules/Php74/Rector/If_/IfToNullCoalescingAssignRector.php b/rules/Php74/Rector/If_/IfToNullCoalescingAssignRector.php index e42a64c1891..671112847a1 100644 --- a/rules/Php74/Rector/If_/IfToNullCoalescingAssignRector.php +++ b/rules/Php74/Rector/If_/IfToNullCoalescingAssignRector.php @@ -20,6 +20,7 @@ use PHPStan\Reflection\Php\PhpPropertyReflection; use PHPStan\Type\MixedType; use PHPStan\Type\TypeCombinator; +use Rector\BetterPhpDocParser\Comment\CommentsMerger; use Rector\PhpParser\Node\BetterNodeFinder; use Rector\PhpParser\Node\Value\ValueResolver; use Rector\Rector\AbstractRector; @@ -37,7 +38,8 @@ final class IfToNullCoalescingAssignRector extends AbstractRector implements Min public function __construct( private readonly BetterNodeFinder $betterNodeFinder, private readonly ValueResolver $valueResolver, - private readonly ReflectionResolver $reflectionResolver + private readonly ReflectionResolver $reflectionResolver, + private readonly CommentsMerger $commentsMerger ) { } @@ -117,7 +119,8 @@ public function refactor(Node $node): ?Expression } $expression = new Expression(new AssignCoalesce($assign->var, $assign->expr)); - $this->mirrorComments($expression, $node); + // keep comments from both the if and the single assign inside it + $this->commentsMerger->keepComments($expression, [$node, $onlyStmt]); return $expression; }