Skip to content

False positive function.alreadyNarrowedType for is_string() on a PHPDoc-only list<string> after isset() stored in a variable, with treatPhpDocTypesAsCertain false (regression in 2.3.0) #15404

Open
phpstan/phpstan-src
#6752

Description

@zajca

Bug report

With treatPhpDocTypesAsCertain: false, PHPStan 2.3.0 reports is_string() as always true for an element whose type comes only from the PHPDoc (@param array{projects?: list<string>}). It happens only when the isset() result is first stored in a variable and that variable is checked afterwards. An inline if (!isset($s['projects'])) return; reports nothing.

2.2.17 reports nothing in either form.

Code snippet that reproduces the problem

<?php declare(strict_types = 1);

namespace Repro;

/** @param array{projects?: list<string>} $s */
function a(array $s): void
{
	$has = isset($s['projects']);
	if (!$has) {
		return;
	}
	foreach ($s['projects'] as $p) {
		if (!is_string($p)) {
			throw new \InvalidArgumentException();
		}
	}
}

Config:

parameters:
	level: max
	treatPhpDocTypesAsCertain: false

Actual output (2.3.0)

13  Call to function is_string() with string will always evaluate to true.
    function.alreadyNarrowedType

Expected output

No error, the same as in 2.2.17 and the same as the inline-isset() form in 2.3.0. The native type of $s is array, so $p is natively mixed. It looks like the conditional expression for $has carries the PHPDoc type of $s['projects'] into the native type.

Related

The same family as #15250, #15169 and #15223, all fixed before 2.3.0: a PHPDoc type leaking into the native type when treatPhpDocTypesAsCertain is false. This path still reproduces on 2.3.0.

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

Yes. The 2.3 speed-up is very noticeable on our codebase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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