Skip to content

Commit 2bef07e

Browse files
committed
BooleanNotHandler
1 parent 53f44a5 commit 2bef07e

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Analyser\Generator\ExprHandler;
4+
5+
use Generator;
6+
use PhpParser\Node\Expr;
7+
use PhpParser\Node\Expr\BooleanNot;
8+
use PhpParser\Node\Stmt;
9+
use PHPStan\Analyser\ExpressionContext;
10+
use PHPStan\Analyser\Generator\ExprAnalysisRequest;
11+
use PHPStan\Analyser\Generator\ExprAnalysisResult;
12+
use PHPStan\Analyser\Generator\ExprHandler;
13+
use PHPStan\Analyser\Generator\GeneratorScope;
14+
use PHPStan\Analyser\SpecifiedTypes;
15+
use PHPStan\DependencyInjection\AutowiredService;
16+
use PHPStan\Type\BooleanType;
17+
use PHPStan\Type\Constant\ConstantBooleanType;
18+
19+
/**
20+
* @implements ExprHandler<BooleanNot>
21+
*/
22+
#[AutowiredService]
23+
final class BooleanNotHandler implements ExprHandler
24+
{
25+
26+
public function supports(Expr $expr): bool
27+
{
28+
return $expr instanceof BooleanNot;
29+
}
30+
31+
public function analyseExpr(Stmt $stmt, Expr $expr, GeneratorScope $scope, ExpressionContext $context, ?callable $alternativeNodeCallback): Generator
32+
{
33+
$result = yield new ExprAnalysisRequest($stmt, $expr->expr, $scope, $context->enterDeep(), $alternativeNodeCallback);
34+
$exprBooleanType = $result->type->toBoolean();
35+
$exprBooleanNativeType = $result->nativeType->toBoolean();
36+
37+
return new ExprAnalysisResult(
38+
$exprBooleanType instanceof ConstantBooleanType ? new ConstantBooleanType(!$exprBooleanType->getValue()) : new BooleanType(),
39+
$exprBooleanNativeType instanceof ConstantBooleanType ? new ConstantBooleanType(!$exprBooleanNativeType->getValue()) : new BooleanType(),
40+
$result->scope,
41+
hasYield: $result->hasYield,
42+
isAlwaysTerminating: $result->isAlwaysTerminating,
43+
throwPoints: $result->throwPoints,
44+
impurePoints: $result->impurePoints,
45+
specifiedTruthyTypes: $result->specifiedFalseyTypes,
46+
specifiedFalseyTypes: $result->specifiedTruthyTypes,
47+
specifiedNullTypes: new SpecifiedTypes(),
48+
);
49+
}
50+
51+
}

tests/PHPStan/Analyser/Generator/data/gnsr.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -561,3 +561,19 @@ function (array $a): void {
561561

562562
assertType("array", $a);
563563
};
564+
565+
function (array $a): void {
566+
if (!($a == [])) {
567+
assertType("non-empty-array", $a);
568+
} else {
569+
assertType("array{}", $a);
570+
}
571+
572+
assertType("array", $a);
573+
};
574+
575+
function (bool $b): void {
576+
assertType('true', !false);
577+
assertType('false', !true);
578+
assertType('bool', !$b);
579+
};

0 commit comments

Comments
 (0)