Given my class
<?php
declare(strict_types=1);
use Illuminate\Support\Collection;
use stdClass;
class PhpstanIssue
{
/**
* @param Collection<Collection<stdClass>> $collection
*
* @return Collection<Foo>
*/
public function whyDoesThisFail(Collection $collection): Collection
{
return $collection
->flatten() // Collection<stdClass>
->map(static function (\stdClass $std): ?Foo {
return Foo::get($std);
}) // should now be Collection<?Foo>
->filter(); // should now be Collection<Foo>
}
}
I am highely confused why phpstan (0.12.64) would fail with:
18: [ERROR] Method PhpstanIssue::whyDoesThisFail() should return
Illuminate\Support\Collection&iterable<Foo> but returns
Illuminate\Support\Collection&iterable<Illuminate\Support\Collection&iterable<stdClass>>. (phpstan)
Why can't phpstan infer the proper result type of this pipe? How can I make phpstan understand the pipe?
I can verify that my code works within a phpunit testcase:
class MyCodeWorks extends TestCase
{
public function testPipeline()
{
$result = (new PhpstanIssue())->whyDoesThisFail(
new Collection(
[
new Collection([new \stdClass(), new \stdClass()]),
new Collection([new \stdClass()]),
]
)
);
self::assertCount(3, $result);
foreach ($result as $item) {
self::assertInstanceOf(Foo::class, $item);
}
}
}
will pass.
My Foo
is just a dummy class for the sake of this question. It's only relevant that it takes a stdClass
instance and transforms it into a ?Foo
one.
class Foo
{
public static function get(\stdClass $std): ?Foo
{
// @phpstan-ignore-next-line
return (bool) $std ? new static() : null;
}
}
Illuminate\Support\Collection
is not a generic class by default. Are you also using Larastan?Collection
class as generic. It should work with your example. Although it also needs a key type. So something likeCollection<int, Collection<int, stdClass>>
But if you don't want to use it, you can also just create your stub files that adds the generic PHPDocs to theCollection
class.