diff --git a/rules/CodeQuality/NodeManipulator/ExprBoolCaster.php b/rules/CodeQuality/NodeManipulator/ExprBoolCaster.php index 898a119e227..68410014fc0 100644 --- a/rules/CodeQuality/NodeManipulator/ExprBoolCaster.php +++ b/rules/CodeQuality/NodeManipulator/ExprBoolCaster.php @@ -9,6 +9,8 @@ use PhpParser\Node\Expr\BinaryOp\NotIdentical; use PhpParser\Node\Expr\BooleanNot; use PhpParser\Node\Expr\Cast\Bool_; +use PHPStan\Type\Type; +use PHPStan\Type\TypeCombinator; use PHPStan\Type\UnionType; use Rector\Core\PhpParser\Node\NodeFactory; use Rector\NodeTypeResolver\NodeTypeResolver; @@ -27,15 +29,15 @@ public function __construct( public function boolCastOrNullCompareIfNeeded(Expr $expr): Expr { - if (! $this->nodeTypeResolver->isNullableType($expr)) { - if (! $this->isBoolCastNeeded($expr)) { + $exprStaticType = $this->nodeTypeResolver->getType($expr); + if (! TypeCombinator::containsNull($exprStaticType)) { + if (! $this->isBoolCastNeeded($expr, $exprStaticType)) { return $expr; } return new Bool_($expr); } - $exprStaticType = $this->nodeTypeResolver->getType($expr); // if we remove null type, still has to be trueable if ($exprStaticType instanceof UnionType) { $unionTypeWithoutNullType = $this->typeUnwrapper->removeNullTypeFromUnionType($exprStaticType); @@ -46,20 +48,19 @@ public function boolCastOrNullCompareIfNeeded(Expr $expr): Expr return new NotIdentical($expr, $this->nodeFactory->createNull()); } - if (! $this->isBoolCastNeeded($expr)) { + if (! $this->isBoolCastNeeded($expr, $exprStaticType)) { return $expr; } return new Bool_($expr); } - private function isBoolCastNeeded(Expr $expr): bool + private function isBoolCastNeeded(Expr $expr, Type $exprType): bool { if ($expr instanceof BooleanNot) { return false; } - $exprType = $this->nodeTypeResolver->getType($expr); if ($exprType->isBoolean()->yes()) { return false; }