Fix #9908: isset condition doesn't refine type#4962
Closed
phpstan-bot wants to merge 5 commits into2.1.xfrom
Closed
Fix #9908: isset condition doesn't refine type#4962phpstan-bot wants to merge 5 commits into2.1.xfrom
phpstan-bot wants to merge 5 commits into2.1.xfrom
Conversation
- In the falsey branch of isset($a['key']), narrow the array variable by removing union members where the key is definitely present with a non-null value - Preserve variable certainty when the array variable might not be defined (using IssetExpr to restore maybe certainty) - Update tagged-unions test expectation to reflect improved narrowing precision - New regression test in tests/PHPStan/Analyser/nsrt/bug-9908.php Closes phpstan/phpstan#9908
| if (!$varType instanceof MixedType) { | ||
| $dimType = $scope->getType($issetExpr->dim); | ||
|
|
||
| if ($dimType instanceof ConstantIntegerType || $dimType instanceof ConstantStringType) { |
Contributor
There was a problem hiding this comment.
I wonder if we have to explicitely check those instanceof.
I think it could work for every dimType.
but this seems to be the same strategy than
phpstan-src/src/Analyser/TypeSpecifier.php
Line 961 in c2da2e8
Contributor
There was a problem hiding this comment.
at the quoted TypeSpecifier location we need the
if ($dimType instanceof ConstantIntegerType || $dimType instanceof ConstantStringType) {
because HasOffsetType constructor types
| $typesToRemove = []; | ||
| foreach ($types as $innerType) { | ||
| $hasOffset = $innerType->hasOffsetValueType($dimType); | ||
| if (!$hasOffset->yes() || !$innerType->getOffsetValueType($dimType)->isNull()->no()) { |
Contributor
There was a problem hiding this comment.
It miss some case with array{foo?: bool} or array{foo: string|null}
Contributor
|
Cherry picked in #4983 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
When using
isset($a['key'])on a union type array, the falsey branch did not narrow the array variable's type. This caused the original union members to leak through after the if-block, even though they were handled by the truthy branch.For example:
The
array{bar: 'string'}type leaked through because the falsey branch ofissetforArrayDimFetchexpressions returned emptySpecifiedTypes(), leaving the array variable's type unchanged. When merged with the truthy branch result, the old type persisted.Changes
src/Analyser/TypeSpecifier.php: In the falseyissethandler for non-variable expressions, added narrowing logic forArrayDimFetchwith constant string/integer dims. The logic iterates over union members of the array variable and removes those where the offset is definitely present (hasOffsetValueType().yes()) and the value is definitely non-null (getOffsetValueType().isNull().no()). When the array variable has uncertain existence (maybecertainty), anIssetExprspecification is included to preserve themaybecertainty.tests/PHPStan/Analyser/nsrt/bug-9908.php: New regression test reproducing the original issue.tests/PHPStan/Analyser/nsrt/tagged-unions.php: Updated test expectation at line 58 to reflect the improved narrowing precision —!isset($foo['C'])now correctly excludes thearray{A: string, C: 1}member that definitely has keyCwith a non-null value.phpstan-baseline.neon: Updatedinstanceof ConstantStringTypecount forTypeSpecifier.php(4→5).Root cause
The
TypeSpecifier::specifyTypesInConditionmethod's falseyissethandler had a code path for non-variableArrayDimFetchexpressions (line ~923) that returned emptySpecifiedTypes()when the offset value was not nullable and the isset check result was uncertain. This meant the array variable received no type narrowing in the falsey branch, causing its original type (including members where isset would be true) to persist and leak through during scope merging after the if-block.The fix carefully avoids two pitfalls:
HasOffsetTyperemoval directly (viaTypeCombinator::remove) would be too aggressive for optional keys, wheretryRemoveunsets the offset entirely.SpecifiedTypessets variable certainty toyes, which would be wrong when the variable might not be defined. The fix usesIssetExprto restoremaybecertainty when needed.Test
The regression test
tests/PHPStan/Analyser/nsrt/bug-9908.phpincludes:test(): Asserts that afterisset($a['bar'])+$a['bar'] = 1, the type isarray{}|array{bar: 1}(not including the originalarray{bar: 'string'})test2(): Verifies the same code passes when used as an argument to a method expectingarray{bar?: int}Fixes phpstan/phpstan#9908