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

PHPStan assumes that an array passed by reference to a callable cannot be changed inside the callable #5428

Closed
steffenweber opened this issue Aug 2, 2021 · 5 comments
Labels
Milestone

Comments

@steffenweber
Copy link

Bug report

$ phpstan --version
PHPStan - PHP Static Analysis Tool 0.12.94

PHPStan seems to assume that an array passed by reference to a callable cannot be changed inside the callable. In the following code snippet, PHPStan claims that the array is empty ("Empty array passed to foreach" on line 14) although it could have been changed by the callable.

Code snippet that reproduces the problem

<?php declare(strict_types = 1);

class HelloWorld
{
	/**
	 * @param string $key
	 * @param callable(array<string> &$tags): string $callback
	 */
	public function get($key, callable $callback): string
	{
		$tags = [];
		$value = $callback($tags);

		foreach ($tags as $tag)
		{
			echo "$tag\n";
		}

		return $value;
	}
}
 ------ -------------------------------- 
  Line   phpstan-testcase.php                    
 ------ -------------------------------- 
  14     Empty array passed to foreach.  
 ------ --------------------------------

https://phpstan.org/r/8912aef0-2aba-4301-b268-647406e82999

Expected output

No errors.

Did PHPStan help you today? Did it make you happy in any way?

PHPStan helped me find unreachable code last Friday. :)

@steffenweber
Copy link
Author

So I guess this issue is similar to issue #5429 but I'm not sure how to tell PHPStan that the callback function is impure. 🤔

@ondrejmirtes
Copy link
Member

In theory PHPStan should be able to pick up the &$tags part and invalidate the variable based on that.

@ondrejmirtes ondrejmirtes added this to the Easy fixes milestone Aug 12, 2021
@phpstan-bot
Copy link
Contributor

@steffenweber After the latest commit in dev-master, PHPStan now reports different result with your code snippet:

@@ @@
-14: Empty array passed to foreach.
+No errors

@ondrejmirtes
Copy link
Member

Fixed: phpstan/phpstan-src@109bf99

@github-actions
Copy link

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 Oct 14, 2021
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

3 participants