-
-
Notifications
You must be signed in to change notification settings - Fork 934
Description
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