Skip to content

Commit

Permalink
[CodeQuality] Handle BooleanNot on SimplifyEmptyCheckOnEmptyArrayRect…
Browse files Browse the repository at this point in the history
…or (#3170)
  • Loading branch information
samsonasik committed Dec 7, 2022
1 parent 84b54c0 commit f8ad265
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ final class ReplaceArrayType

public function isNotEmptyArray(array $values): bool
{
return !($values === []);
return $values !== [];
}

public function isEmptyArrayMixedType(mixed $values): bool
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ final class ReplaceIsArrayCheck

public function isNotEmptyArray($values): bool
{
return is_array($values) && !($values === []);
return is_array($values) && $values !== [];
}

public function isEmptyArrayProperty(): bool
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\Empty_\SimplifyEmptyCheckOnEmptyArrayRectorTest\Fixture;

final class SkipBooleanNotArray
{
public function verify($values): bool
{
return ! empty($values);
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
use PhpParser\Node\Expr;
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\Empty_;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\StaticPropertyFetch;
Expand Down Expand Up @@ -42,33 +44,37 @@ public function getRuleDefinition(): RuleDefinition
*/
public function getNodeTypes(): array
{
return [Empty_::class];
return [Empty_::class, BooleanNot::class];
}

/**
* @param Empty_ $node $node
* @param Empty_|BooleanNot $node $node
*/
public function refactorWithScope(Node $node, Scope $scope): ?Node
{
if (! $this->isAllowedExpr($node->expr)) {
return null;
}
if ($node instanceof BooleanNot) {
if ($node->expr instanceof Empty_ && $this->isAllowedExpr($node->expr->expr, $scope)) {
return new NotIdentical($node->expr->expr, new Array_());
}

if (! $scope->getType($node->expr) instanceof ArrayType) {
return null;
}

if ($this->exprAnalyzer->isNonTypedFromParam($node->expr)) {
if (! $this->isAllowedExpr($node->expr, $scope)) {
return null;
}

return new Identical($node->expr, new Array_());
}

private function isAllowedExpr(Expr $expr): bool
private function isAllowedExpr(Expr $expr, Scope $scope): bool
{
if (! $scope->getType($expr) instanceof ArrayType) {
return false;
}

if ($expr instanceof Variable) {
return true;
return ! $this->exprAnalyzer->isNonTypedFromParam($expr);
}

if ($expr instanceof PropertyFetch) {
Expand Down

0 comments on commit f8ad265

Please sign in to comment.