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
13 changes: 7 additions & 6 deletions rules/CodeQuality/NodeManipulator/ExprBoolCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand All @@ -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;
}
Expand Down