Skip to content

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

@tlamy

Description

@tlamy

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions