Skip to content

False positive about a non-empty-array seen as array when more elements could be appended in an if condition #7996

@asprega

Description

@asprega

Bug report

I took a look at all the issues that i found about non empty arrays and this seems to not have been filed. I apologize in advance if this is a duplicate instead.

A non-empty-array is seen as just array after being used in a loop in which other elements could be pushed into the array inside of an if branch. If I remove the if and just make the push "certain", PHPStan detects the non empty array correctly.

Code snippet that reproduces the problem

<?php declare(strict_types = 1);

class HelloWorld
{
    /**
     * @param non-empty-array<\stdclass> $inputArray
     * @return non-empty-array<\stdclass>
     */
    public function filter(array $inputArray): array
	{
        $currentItem = reset($inputArray);
        $outputArray = [$currentItem]; // $outputArray is now non-empty-array
		
        while ($nextItem = next($inputArray)) {
			if (rand(1, 2) === 1) {
				// The fact that this is into an if, reverts type of $outputArray to array 
			    $outputArray[] = $nextItem;
			}
        }

        return $outputArray;
    }
}

Produces: Method HelloWorld::filter() should return non-empty-array<stdClass> but returns array<int, stdClass>.

https://phpstan.org/r/fef4c35b-49b3-4249-baa2-cd776a79281f

Expected output

Type of the return value should be inferred correctly, thus non-empty-array.

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

To make sure the issue wasn't fixed already I just updated to the latest version and it always amazes me how PHPStan keeps improving and finds always more and more issues at every update. Thanks for the amazing work <3

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions