Skip to content
Open
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
21 changes: 21 additions & 0 deletions src/Analyser/TypeSpecifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -2934,6 +2934,27 @@ private function resolveNormalizedIdentical(Expr\BinaryOp\Identical $expr, Scope
}
}

// (string)$expr === '' - propagate narrowing to inner expression
if (
!$context->null()
&& $unwrappedLeftExpr instanceof Expr\Cast\String_
) {
$rightConstantStrings = $rightType->getConstantStrings();
if (count($rightConstantStrings) === 1 && $rightConstantStrings[0]->getValue() === '') {
// Types that produce '' when cast to string: null, false, ''
$castToEmptyStringType = TypeCombinator::union(
new NullType(),
new ConstantBooleanType(false),
new ConstantStringType(''),
);
$innerExpr = $unwrappedLeftExpr->expr;
$result = $this->create($leftExpr, $rightType, $context, $scope)->setRootExpr($expr);
return $result->unionWith(
$this->create($innerExpr, $castToEmptyStringType, $context, $scope)->setRootExpr($expr),
);
}
}

$expressions = $this->findTypeExpressionsFromBinaryOperation($scope, $expr);
if ($expressions !== null) {
$exprNode = $expressions[0];
Expand Down
42 changes: 42 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-8231.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php // lint >= 8.0

declare(strict_types = 1);

namespace Bug8231;

use function PHPStan\Testing\assertType;

function foo(string $x): void {}

function test(string|null $x): void {
if ((string)$x !== '') {
assertType('non-empty-string', $x);
foo($x);
}
}

function testIdentical(string|null $x): void {
if ((string)$x === '') {
assertType("''|null", $x);
} else {
assertType('non-empty-string', $x);
}
}

function testInt(int|null $x): void {
if ((string)$x !== '') {
assertType('int', $x);
}
}

function testIntString(int|string|null $x): void {
if ((string)$x !== '') {
assertType('int|non-empty-string', $x);
}
}

function testBool(bool|string|null $x): void {
if ((string)$x !== '') {
assertType('non-empty-string|true', $x);
}
}
Loading