Skip to content

Commit

Permalink
[CodeQuality] Skip increment variable on else on TernaryFalseExpressi…
Browse files Browse the repository at this point in the history
…onToIfRector (#5867)

* [CodeQuality] Skip increment variable on if and else on TernaryFalseExpressionToIfRector

* [CodeQuality] Skip increment variable on else on TernaryFalseExpressionToIfRector

* fix
  • Loading branch information
samsonasik committed May 10, 2024
1 parent 48fc55d commit ca2988e
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ final class IncludeNoSideEffectExpr
{
$value ? $someMethod->call($value) : true;
}

public function run2($value, $someMethod, $variable)
{
$value ? $someMethod->call($value) : $variable;
}
}

?>
Expand All @@ -24,6 +29,13 @@ final class IncludeNoSideEffectExpr
$someMethod->call($value);
}
}

public function run2($value, $someMethod, $variable)
{
if ($value) {
$someMethod->call($value);
}
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Expression\TernaryFalseExpressionToIfRector\Fixture;

final class SkipIncrementVariableOnElse
{
public function run($id)
{
$success = $failed = 0;
$id ? ++$success : ++$failed;

if ($success > $failed) {
return $success;
}

return $failed;
}

public function run2($id)
{
$success = $failed = 0;
! $id ? ++$failed : ++$success;

if ($success > $failed) {
return $success;
}

return $failed;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PHPStan\Analyser\Scope;
use Rector\DeadCode\SideEffect\SideEffectNodeDetector;
use Rector\NodeAnalyzer\ExprAnalyzer;
use Rector\Rector\AbstractScopeAwareRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
Expand All @@ -21,7 +22,7 @@
final class TernaryFalseExpressionToIfRector extends AbstractScopeAwareRector
{
public function __construct(
private readonly SideEffectNodeDetector $sideEffectNodeDetector
private readonly ExprAnalyzer $exprAnalyzer
) {
}

Expand Down Expand Up @@ -77,10 +78,7 @@ public function refactorWithScope(Node $node, Scope $scope): ?Node
return null;
}

if ($this->sideEffectNodeDetector->detect(
$ternary->else,
$scope
) || $this->sideEffectNodeDetector->detectCallExpr($ternary->else, $scope)) {
if (! $ternary->else instanceof Variable && $this->exprAnalyzer->isDynamicExpr($ternary->else)) {
return null;
}

Expand Down

0 comments on commit ca2988e

Please sign in to comment.