Skip to content

Commit

Permalink
TypeSpecifier: Narrow (string) $expr like $expr != false
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm authored and ondrejmirtes committed Sep 2, 2024
1 parent 39892b6 commit 3d17f51
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
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);
}
}

0 comments on commit 3d17f51

Please sign in to comment.