Skip to content

Commit 319e98b

Browse files
staabmondrejmirtes
authored andcommitted
TypeSpecifier: Narrow (int) $expr like $expr != false
1 parent f4c8870 commit 319e98b

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/Analyser/TypeSpecifier.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,15 +196,17 @@ public function specifyTypesInCondition(
196196
$context,
197197
$rootExpr,
198198
);
199-
} elseif ($expr instanceof Expr\Cast\String_) {
199+
} elseif (
200+
$expr instanceof Expr\Cast\String_
201+
|| $expr instanceof Expr\Cast\Int_
202+
|| $expr instanceof Expr\Cast\Bool_
203+
) {
200204
return $this->specifyTypesInCondition(
201205
$scope,
202206
new Node\Expr\BinaryOp\NotEqual($expr->expr, new ConstFetch(new Name\FullyQualified('false'))),
203207
$context,
204208
$rootExpr,
205209
);
206-
} elseif ($expr instanceof Expr\Cast\Bool_) {
207-
return $this->resolveEqual(new Expr\BinaryOp\Equal($expr->expr, new ConstFetch(new Name\FullyQualified('true'))), $scope, $context, $rootExpr);
208210
} elseif ($expr instanceof Node\Expr\BinaryOp\Equal) {
209211
return $this->resolveEqual($expr, $scope, $context, $rootExpr);
210212
} elseif ($expr instanceof Node\Expr\BinaryOp\NotEqual) {

tests/PHPStan/Analyser/nsrt/narrow-bool-cast.php renamed to tests/PHPStan/Analyser/nsrt/narrow-cast.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,24 @@ function castString($x, string $s, bool $b) {
4848
assertType('string', $s);
4949
}
5050
}
51+
52+
/** @param int<-5, 5> $x */
53+
function castInt($x, string $s, bool $b) {
54+
if ((int) $x) {
55+
assertType('int<-5, -1>|int<1, 5>', $x);
56+
} else {
57+
assertType('0', $x);
58+
}
59+
60+
if ((int) $b) {
61+
assertType('true', $b);
62+
} else {
63+
assertType('false', $b);
64+
}
65+
66+
if ((int) strpos($s, 'xy')) {
67+
assertType('non-falsy-string', $s);
68+
} else {
69+
assertType('string', $s);
70+
}
71+
}

0 commit comments

Comments
 (0)