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,36 @@
<?php

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

class IfAssignCond
{
public function run()
{
if ($base64 = base64_encode('')) {
return 5;
}

return '10';
}
}

?>
-----
<?php

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

class IfAssignCond
{
public function run()
{
$base64 = base64_encode('');
if ($base64 !== '' && $base64 !== '0') {
return 5;
}

return '10';
}
}

?>
19 changes: 18 additions & 1 deletion rules/CodeQuality/Rector/If_/ExplicitBoolCompareRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
use PhpParser\Node\Expr\BinaryOp\BooleanOr;
Expand All @@ -21,7 +22,9 @@
use PhpParser\Node\Scalar\DNumber;
use PhpParser\Node\Scalar\LNumber;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\ElseIf_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
Expand Down Expand Up @@ -85,8 +88,9 @@ public function getNodeTypes(): array

/**
* @param If_|ElseIf_|Ternary $node
* @return null|Stmt[]|Node
*/
public function refactor(Node $node): ?Node
public function refactor(Node $node): null|array|Node
{
// skip short ternary
if ($node instanceof Ternary && ! $node->if instanceof Expr) {
Expand Down Expand Up @@ -115,6 +119,19 @@ public function refactor(Node $node): ?Node
return null;
}

if ($node instanceof If_ && $node->cond instanceof Assign && $binaryOp->left instanceof NotIdentical && $binaryOp->right instanceof NotIdentical) {
$expression = new Expression($node->cond);
$binaryOp->left->left = $node->cond->var;
$binaryOp->right->left = $node->cond->var;

$node->cond = $binaryOp;

return [
$expression,
$node,
];
}

$node->cond = $binaryOp;

return $node;
Expand Down