phpstan-src icon indicating copy to clipboard operation
phpstan-src copied to clipboard

Fix !isset() with ArrayDimFetch

Open staabm opened this issue 1 year ago • 6 comments
trafficstars

the current 1.10.x handles the !isset() context for variables only. it works only correct for !isset($var) and its implications on the variable.

with this PR we add support for !isset($var['abc']) which means

  • we handle implications on $var's array-shape based on the $var['abc']-offset type (based on nullability and optional/non-optional offset state)

with this PR we know when

  • offsets can only be null or non-null in true/falsey-context
  • offsets may or will not exist in falsey-context
  • on array-shapes with just a single offset we know about the certainty implications on the var in falsey-context

the newly added tests in tests/PHPStan/Analyser/data/falsy-isset.php best reflect the new type inference implications.

closes https://github.com/phpstan/phpstan/issues/9908 closes https://github.com/phpstan/phpstan/issues/9426 closes https://github.com/phpstan/phpstan/issues/8724 closes https://github.com/phpstan/phpstan/issues/5128

staabm avatar Nov 30 '23 13:11 staabm

the remaining error is strange

Offset 'input' does not exist on array{input: Bug8724b\Input}|array{label: string}.

I have not yet an idea about it... but maybe we should even expect this error?

type-wise the offset label always exists, which means the null-coalescing is unnecessary and the code right to ?? is actually dead code..?

/**
 * @param array{label:string}|array{input:Input} $data
 */
function test(array $data): void
{
	$label = $data['label'] ?? $data['input']->getLabel();
}

staabm avatar Nov 30 '23 14:11 staabm

This pull request has been marked as ready for review.

phpstan-bot avatar Nov 30 '23 14:11 phpstan-bot

ohh I get it now.. I think the PR fixes the initial reported snippet but not the one posted within a followup comment

clxmstaab avatar Nov 30 '23 14:11 clxmstaab

Can you please explain in your own words what are the faults of the current handling (as of 1.10.x) and what approach this PR does to fix that?

ondrejmirtes avatar Nov 30 '23 14:11 ondrejmirtes

I added a description to the PR

staabm avatar Nov 30 '23 15:11 staabm

Alright, what about nested expressions like $foo['abc']['def']? Does it work correctly?

ondrejmirtes avatar Nov 30 '23 15:11 ondrejmirtes