Skip to content

Fix phpstan/phpstan#8231: Missing type narrowing after (string)$value#5355

Open
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-4xe7wmz
Open

Fix phpstan/phpstan#8231: Missing type narrowing after (string)$value#5355
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-4xe7wmz

Conversation

@phpstan-bot
Copy link
Copy Markdown
Collaborator

Summary

When comparing a string cast expression with an empty string (e.g., (string)$x !== ''), PHPStan was not propagating the type narrowing back to the inner expression. This meant that $x of type string|null was not narrowed to string (or non-empty-string) inside the condition branch, causing false positive errors.

Changes

  • Added a new block in src/Analyser/TypeSpecifier.php in resolveNormalizedIdentical() to handle Cast\String_ expressions
  • When (string)$expr === '' is encountered, the narrowing is propagated to $expr using the union type null|false|'' (the types that produce '' when cast to string)
  • This works in both contexts: === '' narrows to those types, !== '' removes them

Root cause

TypeSpecifier::resolveNormalizedIdentical() already handled unwrapping AlwaysRememberedExpr to propagate type narrowing to inner expressions, but did not handle Expr\Cast\String_. When (string)$x !== '' was analysed, the cast expression (string)$x was correctly narrowed to non-empty-string, but the underlying variable $x retained its original string|null type because the narrowing was never propagated through the cast.

Test

Added tests/PHPStan/Analyser/nsrt/bug-8231.php with assertions covering:

  • string|null narrowed to non-empty-string after (string)$x !== ''
  • string|null narrowed to ''|null after (string)$x === ''
  • int|null narrowed to int (removing null)
  • int|string|null narrowed to int|non-empty-string
  • bool|string|null narrowed to non-empty-string|true

Fixes phpstan/phpstan#8231

- Added handling in TypeSpecifier::resolveNormalizedIdentical for Cast\String_ expressions
- When (string)$x === '' or (string)$x !== '', propagate narrowing to inner expression $x
- Types that produce '' when cast to string (null, false, '') are used as the narrowing type
- New regression test in tests/PHPStan/Analyser/nsrt/bug-8231.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant