Skip to content

Commit 3d17f51

Browse files
staabmondrejmirtes
authored andcommitted
TypeSpecifier: Narrow (string) $expr like $expr != false
1 parent 39892b6 commit 3d17f51

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/Analyser/TypeSpecifier.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,13 @@ public function specifyTypesInCondition(
196196
$context,
197197
$rootExpr,
198198
);
199+
} elseif ($expr instanceof Expr\Cast\String_) {
200+
return $this->specifyTypesInCondition(
201+
$scope,
202+
new Node\Expr\BinaryOp\NotEqual($expr->expr, new ConstFetch(new Name\FullyQualified('false'))),
203+
$context,
204+
$rootExpr,
205+
);
199206
} elseif ($expr instanceof Expr\Cast\Bool_) {
200207
return $this->resolveEqual(new Expr\BinaryOp\Equal($expr->expr, new ConstFetch(new Name\FullyQualified('true'))), $scope, $context, $rootExpr);
201208
} elseif ($expr instanceof Node\Expr\BinaryOp\Equal) {

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,24 @@ function doFoo(string $x, array $arr): void {
2727
}
2828
assertType('array{}|array{string}', $matches);
2929
}
30+
31+
/** @param int<-5, 5> $x */
32+
function castString($x, string $s, bool $b) {
33+
if ((string) $x) {
34+
assertType('int<-5, -1>|int<1, 5>', $x);
35+
} else {
36+
assertType('0', $x);
37+
}
38+
39+
if ((string) $b) {
40+
assertType('true', $b);
41+
} else {
42+
assertType('false', $b);
43+
}
44+
45+
if ((string) strrchr($s, 'xy')) {
46+
assertType('string', $s); // could be non-empty-string
47+
} else {
48+
assertType('string', $s);
49+
}
50+
}

0 commit comments

Comments
 (0)