Skip to content
Merged
Show file tree
Hide file tree
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
7 changes: 7 additions & 0 deletions src/Analyser/TypeSpecifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,13 @@ public function specifyTypesInCondition(
$context,
$rootExpr,
);
} elseif ($expr instanceof Expr\Cast\String_) {
return $this->specifyTypesInCondition(
$scope,
new Node\Expr\BinaryOp\NotEqual($expr->expr, new ConstFetch(new Name\FullyQualified('false'))),
$context,
$rootExpr,
);
} elseif ($expr instanceof Expr\Cast\Bool_) {
return $this->resolveEqual(new Expr\BinaryOp\Equal($expr->expr, new ConstFetch(new Name\FullyQualified('true'))), $scope, $context, $rootExpr);
} elseif ($expr instanceof Node\Expr\BinaryOp\Equal) {
Expand Down
21 changes: 21 additions & 0 deletions tests/PHPStan/Analyser/nsrt/narrow-bool-cast.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,24 @@ function doFoo(string $x, array $arr): void {
}
assertType('array{}|array{string}', $matches);
}

/** @param int<-5, 5> $x */
function castString($x, string $s, bool $b) {
if ((string) $x) {
assertType('int<-5, -1>|int<1, 5>', $x);
} else {
assertType('0', $x);
}

if ((string) $b) {
assertType('true', $b);
} else {
assertType('false', $b);
}

if ((string) strrchr($s, 'xy')) {
assertType('string', $s); // could be non-empty-string
} else {
assertType('string', $s);
}
}
Loading