Skip to content

Commit

Permalink
[CodeQuality] Add Equal and NotEqual support on SimplifyIfReturnBoolR…
Browse files Browse the repository at this point in the history
…ector (#5697)
  • Loading branch information
samsonasik committed Mar 7, 2024
1 parent 7507136 commit 4a1880b
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 1 deletion.
@@ -0,0 +1,73 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector\Fixture;

class EqualNotEqual
{
public function notTrue($value)
{
if ($value != '0') {
return true;
}

return false;
}

public function notFalse($value)
{
if ($value != '0') {
return false;
}

return true;
}

public function eqTrue($value)
{
if ($value == '0') {
return true;
}

return false;
}

public function eqFalse($value)
{
if ($value == '0') {
return false;
}

return true;
}
}

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector\Fixture;

class EqualNotEqual
{
public function notTrue($value)
{
return $value != '0';
}

public function notFalse($value)
{
return $value == '0';
}

public function eqTrue($value)
{
return $value == '0';
}

public function eqFalse($value)
{
return $value != '0';
}
}

?>
15 changes: 14 additions & 1 deletion rules/CodeQuality/Rector/If_/SimplifyIfReturnBoolRector.php
Expand Up @@ -6,7 +6,9 @@

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\Equal;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\BinaryOp\NotEqual;
use PhpParser\Node\Expr\BinaryOp\NotIdentical;
use PhpParser\Node\Expr\BooleanNot;
use PhpParser\Node\Stmt\Else_;
Expand Down Expand Up @@ -153,7 +155,7 @@ private function shouldSkipIfAndReturn(If_ $if, Return_ $return): bool
return ! $this->valueResolver->isTrueOrFalse($return->expr);
}

return ! $if->cond instanceof NotIdentical;
return ! $if->cond instanceof NotIdentical && ! $if->cond instanceof NotEqual;
}

private function processReturnTrue(If_ $if, Return_ $nextReturn): Return_
Expand All @@ -175,6 +177,12 @@ private function processReturnFalse(If_ $if, Return_ $nextReturn): ?Return_
return new Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded($notIdentical));
}

if ($if->cond instanceof Equal) {
$notIdentical = new NotEqual($if->cond->left, $if->cond->right);

return new Return_($this->exprBoolCaster->boolCastOrNullCompareIfNeeded($notIdentical));
}

if (! $nextReturn->expr instanceof Expr) {
return null;
}
Expand Down Expand Up @@ -241,6 +249,11 @@ private function resolveReturn(Expr $innerExpr, If_ $if, Return_ $return): ?Retu
return $this->processReturnTrue($if, $return);
}

if ($if->cond instanceof NotEqual && $this->valueResolver->isTrue($expr)) {
$if->cond = new Equal($if->cond->left, $if->cond->right);
return $this->processReturnTrue($if, $return);
}

return $this->processReturnFalse($if, $return);
}

Expand Down

0 comments on commit 4a1880b

Please sign in to comment.