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

False Positive: string|null inferred although null check is in place #7973

Closed
tlamy opened this issue Sep 9, 2022 · 2 comments · Fixed by phpstan/phpstan-src#1716
Closed

Comments

@tlamy
Copy link

tlamy commented Sep 9, 2022

Bug report

phpstan falsely reports string|null type although proper null check is done in ternary.

Code snippet that reproduces the problem

https://phpstan.org/r/3962507d-a02a-447b-9b46-23e08110b40b

<?php declare(strict_types = 1);

function createFromString(string $timespec): DateTime {
	try {
		return new DateTime($timespec, new DateTimeZone('UTC'));
	} catch (Exception) {
		throw new InvalidArgumentException(sprintf('Invalid timespec "%s"', $timespec));
	}
}

$rows = [
	['timespec'=>null],
	['timespec'=>'2020-01-01T01:02:03+08:00'],
];

$result = [];
foreach($rows as $row) {
	$result[] = ($row['timespec'] ?? null) !== null ? createFromString($row['timespec']) : null;
}

Expected output

No error.

Acutal output

Parameter #1 $timespec of function createFromString expects string, string|null given

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

Phpstan helps me every day, and the speed in which issues are fixed is absolutely amazing!

@ondrejmirtes
Copy link
Member

Thank you for your kind words! 😊

/cc @rvanvelzen This looks like something that should have been fixed by your recent PR but wasn't.

@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 15, 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

Successfully merging a pull request may close this issue.

2 participants