Skip to content
Merged
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
39 changes: 17 additions & 22 deletions rules/CodeQuality/Rector/If_/ArrayExplicitBoolCompareRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\BinaryOp\NotIdentical;
use PhpParser\Node\Expr\BooleanNot;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\ElseIf_;
use PhpParser\Node\Stmt\If_;
use Rector\CodeQuality\NodeAnalyzer\ExplicitBoolConditionResolver;
use Rector\CodeQuality\ValueObject\ExplicitBoolCondition;
use Rector\NodeTypeResolver\TypeAnalyzer\ArrayTypeAnalyzer;
use Rector\Rector\AbstractRector;
use Rector\RuleDoc\CodeSample\CodeSample;
Expand All @@ -27,7 +26,6 @@ final class ArrayExplicitBoolCompareRector extends AbstractRector
{
public function __construct(
private readonly ArrayTypeAnalyzer $arrayTypeAnalyzer,
private readonly ExplicitBoolConditionResolver $explicitBoolConditionResolver,
) {
}

Expand Down Expand Up @@ -75,39 +73,36 @@ public function getNodeTypes(): array
*/
public function refactor(Node $node): ?Node
{
$explicitBoolCondition = $this->explicitBoolConditionResolver->resolve($node);
if (! $explicitBoolCondition instanceof ExplicitBoolCondition) {
// skip short ternary
if ($node instanceof Ternary && ! $node->if instanceof Expr) {
return null;
}

$expr = $explicitBoolCondition->getConditionNode();
if (! $this->arrayTypeAnalyzer->isArrayType($expr)) {
return null;
if ($node->cond instanceof BooleanNot) {
$conditionNode = $node->cond->expr;
$isNegated = true;
} else {
$conditionNode = $node->cond;
$isNegated = false;
}

$binaryOp = $this->resolveArray($explicitBoolCondition->isNegated(), $expr);
if (! $binaryOp instanceof Expr) {
// cheap bail - rule only ever rewrites a bare variable, skip costly type resolution otherwise
if (! $conditionNode instanceof Variable) {
return null;
}

$node->cond = $binaryOp;

return $node;
}

private function resolveArray(bool $isNegated, Expr $expr): Identical|NotIdentical|null
{
if (! $expr instanceof Variable) {
// array type already excludes mixed and bool, so a single native type check is enough
if (! $this->arrayTypeAnalyzer->isArrayType($conditionNode)) {
return null;
}

$array = new Array_([]);

// compare === []
if ($isNegated) {
return new Identical($expr, $array);
}
$node->cond = $isNegated
? new Identical($conditionNode, $array)
: new NotIdentical($conditionNode, $array);

return new NotIdentical($expr, $array);
return $node;
}
}
Loading