Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try fixing assigning array offsets on possibly undefined nested array offsets #3865

Draft
wants to merge 4 commits into
base: 2.1.x
Choose a base branch
from

Conversation

ondrejmirtes
Copy link
Member

No description provided.

@ondrejmirtes
Copy link
Member Author

<?php

use function PHPStan\Testing\assertType;

function doFoo(int $i): void
{
	$array = [];

	$array[$i]['bar'] = 1;
	$array[$i]['baz'] = 2;

	// on line 10 PHPStan assigns:
	// 1) $array[$i]['baz'] to 2
	// 2) $array[$i] to array{bar: 1, baz: 2}
	// 3) $array = from non-empty-array<int, array{bar: 1}> to non-empty-array<int, array{bar: 1, baz: 2}>
	// but step 3) is basically wrong for most code because assigning "baz" might be on a different offset than array{bar: 1} is on
	// but somehow we need to continue doing this if this PR is supposed to be successful

	assertType('non-empty-array<int, array{bar: 1, baz: 2}>', $array);
}

@ondrejmirtes
Copy link
Member Author

I realized the above problem could be fixed with a new accessory "ArraySize" type. When doing $array[$i]['baz'] = 2; and by knowing that $array[$i] already exists and by knowing that $array has size 1, we could overwrite the array with a new type. So instead of:

non-empty-array<int, array{bar: 1, baz?: 2}>

We could actually end up with:

non-empty-array<int, array{bar: 1, baz: 2}>

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