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

Null coalescing operator on multi-level array access #4592

Closed
derrabus opened this issue Feb 23, 2021 · 3 comments
Closed

Null coalescing operator on multi-level array access #4592

derrabus opened this issue Feb 23, 2021 · 3 comments
Labels
Milestone

Comments

@derrabus
Copy link

Bug report

If I apply the coalescing operator to a two-level array access ($foo[$one][$two]) where the second level is guaranteed to be set, phpstan does not take into account that the first level might be undefined.

If you run phpstan on the snippet below, it will complain that $name can never be null in sayHello1(). In sayHello2() however, the two levels are inverted. Here, the behavior is correct.

Code snippet that reproduces the problem

class HelloWorld
{
	/**
	 * @var array<string, array{name: string, email: string}>
	 */
	private array $contacts1 = [];
	
	/**
	 * @var array{names: array<string, string>, emails: array<string, string>}
	 */
	private array $contacts2 = ['names' => [], 'emails' => []];
	
	public function sayHello1(string $id): void
	{
		$name = $this->contacts1[$id]['name'] ?? null;
		if ($name === null) {
			throw new \InvalidArgumentException('Unknown contact.');
		}
		
		echo "Hello $name!";
	}

	public function sayHello2(string $id): void
	{
		$name = $this->contacts2['names'][$id] ?? null;
		if ($name === null) {
			throw new \InvalidArgumentException('Unknown contact.');
		}
		
		echo "Hello $name!";
	}
}

https://phpstan.org/r/766659f0-7300-4297-81ff-f32314bbb9ac

Expected output

The code should not produce any errors.

@ondrejmirtes
Copy link
Member

Fixed: phpstan/phpstan-src@3b17acc

@derrabus
Copy link
Author

Awesome! ❤️

@github-actions
Copy link

github-actions bot commented Mar 4, 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 4, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants