Skip to content
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Rector\Tests\Php70\Rector\Ternary\TernaryToNullCoalescingRector\Fixture;

final class KeepInnerTernaryParenthesesInConcat
{
public function run($a, $b)
{
return isset($a) ? $a : ('R' . ($b == 1? '' : 'ector'));
}
}

?>
-----
<?php

namespace Rector\Tests\Php70\Rector\Ternary\TernaryToNullCoalescingRector\Fixture;

final class KeepInnerTernaryParenthesesInConcat
{
public function run($a, $b)
{
return $a ?? ('R' . ($b == 1? '' : 'ector'));
}
}

?>
31 changes: 31 additions & 0 deletions src/PhpParser/Printer/BetterStandardPrinter.php
Original file line number Diff line number Diff line change
Expand Up @@ -544,15 +544,46 @@ private function wrapBinaryOpWithBrackets(Node $node): void

if ($node->left instanceof BinaryOp &&
$node->left->getAttribute(AttributeKey::ORIGINAL_NODE) instanceof Node) {
$this->keepTernaryOperandParentheses($node->left);
$node->left->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}

if ($node->right instanceof BinaryOp &&
$node->right->getAttribute(AttributeKey::ORIGINAL_NODE) instanceof Node) {
$this->keepTernaryOperandParentheses($node->right);
$node->right->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
}

/**
* The binary op is about to be reprinted, while its unchanged ternary operand is still format-preserved,
* which prints it without its original parentheses
*
* @see https://github.com/rectorphp/rector-src/issues/8910
*/
private function keepTernaryOperandParentheses(BinaryOp $binaryOp): void
{
$originalBinaryOp = $binaryOp->getAttribute(AttributeKey::ORIGINAL_NODE);
if (! $originalBinaryOp instanceof BinaryOp || ! $this->origTokens instanceof TokenStream) {
return;
}

foreach ([$binaryOp->left, $binaryOp->right] as $key => $operand) {
if (! $operand instanceof Ternary) {
continue;
}

$originalOperand = $key === 0 ? $originalBinaryOp->left : $originalBinaryOp->right;
if ($operand->getAttribute(AttributeKey::ORIGINAL_NODE) !== $originalOperand) {
continue;
}

if ($this->origTokens->haveParens($operand->getStartTokenPos(), $operand->getEndTokenPos())) {
$operand->setAttribute(AttributeKey::WRAPPED_IN_PARENTHESES, true);
}
}
}

/**
* @see https://github.com/rectorphp/rector/issues/9800
*/
Expand Down
Loading