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

Not respecting previous null check #4357

Closed
allejo opened this issue Jan 11, 2021 · 2 comments
Closed

Not respecting previous null check #4357

allejo opened this issue Jan 11, 2021 · 2 comments
Labels
Milestone

Comments

@allejo
Copy link
Contributor

allejo commented Jan 11, 2021

Bug report

It looks like null checks that happen previous and cause an exit from a function are ignored. i.e. After the null check, the variable is still considered "nullable."

Code snippet that reproduces the problem

<?php declare(strict_types = 1);

class Sample {
	/** @var null|array<string, string> */
	private $arr = null;
	
	public function test(): void {
		if ($this->arr === null) {
			return;
		}
		
		unset($this->arr['hello']);
		
		if (count($this->arr) === 0) {
			$this->arr = null;
		}
	}
}

https://phpstan.org/r/a79d1e2f-932f-4c40-8e92-530baa0a3fb8

Expected output

This should work the same and not require an explicit null check like so,

if ($this->arr !== null && count($this->arr) === 0) {
    $this->arr = null;
}
@phpstan-bot
Copy link
Contributor

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

@@ @@
-PHP 8.0 (1 error)
-==========
-
-14: Parameter #1 $value of function count expects array|Countable, array<string, string>|null given.
-
-PHP 7.1 – 7.4 (1 error)
-==========
-
-14: Parameter #1 $var of function count expects array|Countable, array<string, string>|null given.
+No errors

@allejo allejo closed this as completed Jan 20, 2022
ondrejmirtes added a commit to phpstan/phpstan-src that referenced this issue Jan 21, 2022
@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 Feb 21, 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

3 participants