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

If array keys are known, they should be used to infer lookup types #6108

Closed
MaartenStaa opened this issue Nov 29, 2021 · 3 comments
Closed

Comments

@MaartenStaa
Copy link

MaartenStaa commented Nov 29, 2021

Feature request

If I have two arrays, each of which have a defined shape, PHPStan should be able to figure out the value of array lookups. For example:

<?php declare(strict_types = 1);

/**
 * @return array{
 *	a: int[],
 * 	b: int[],
 *	c: bool
 * }
 */
function foo(): array {
	return [
		'a' => [1, 2],
		'b' => [3, 4, 5],
		'c' => true,
	];
}

$x = foo();
$test = ['a' => true, 'b' => false];
foreach ($test as $key => $value) {
	if ($value) {
		foreach ($x[$key] as $id) {
			echo $id, PHP_EOL;
		}
	}
}

This results in an error on the foreach line: "Argument of an invalid type array|bool supplied for foreach, only iterables are supported." (playground link). However, PHPStan should "know" that $key has type 'a'|'b', both of which would be keys on $x that contain values that are valid to iterate over.

@staabm
Copy link
Contributor

staabm commented Dec 2, 2021

A workaround is to introduce a temp var before the inner foreach, it works like expected
https://phpstan.org/r/8c20db8c-1f23-4af1-bbff-35c5ec6b9cb7

@ondrejmirtes
Copy link
Member

This was recently fixed and works in PHPStan 1.4.4.

@github-actions
Copy link

github-actions bot commented Mar 5, 2022

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 5, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants