Phpstan: [SOLUTION: @template-covariant] Complex generics and inheritance issue I don't understand

Created on 25 Nov 2020  路  3Comments  路  Source: phpstan/phpstan

Hello there! First, I'd like to thank anyone who will investigate time on this issue. :pray:

Now here's the playground : https://phpstan.org/r/2bc5b4eb-5104-49ee-8c16-06ee78a254dd

Basically, I have some interfaces and classes that represents Events in my application. Then I have a helper class EventBusDispatcher that allows to create complex events and publish them for a specific user, which takes simple arguments (and is used in many places in our code). One of the complexity is that an event can be triggered as a single change (which publishes an AbsenceCreated event) vs many changes (which publishes a BatchAbsenceCreated event). An event that can be converted from a single to batch implements BatchableEvent.

I tried to use generics to represent the types of Events/BatchEvent/BatchableEvent that are allowed into the method of the EventBusDispatcher, but I get this error whenever I call it from some code (like the Controller in the playground at the very end) :

Parameter #1 $eventClass of method App\Infrastructure\Shared\Bus\EventBusDispatcher::dispatchEvents() expects class-string<App\Domain\Shared\Event\BatchableEvent<App\Domain\Shared\Event\BatchEvent>>, string given.

I don't understand, as the argument given is AbsenceCreated::class, which is a class-string<AbsenceCreated> basically, and AbsenceCreated extends AbsenceEvent which implements BatchableEvent and sets the proper @implements BatchableEvent<BatchAbsenceEvent>, and BatchAbsenceEvent extends BatchEvent. In my mind, this should all work nicely.

But in order for PhpStan to pass, I had to change the EventBusDispatcher::dispatchEvents method's PHPDocs from @param class-string<BatchableEvent<BatchEvent>> $eventClass (what I expected to be correct) to @param class-string<mixed> $eventClass (which is sad...).

Any idea what I did wrong in all this ? Is it a bug in PhpStan ?
gnutix

Most helpful comment

All 3 comments

Maybe it could be a suggestion for that error message? :D

PHPStan\Type\Type::accepts() does not say the reason for not accepting so it's not possible to detect that in rules...

Was this page helpful?
0 / 5 - 0 ratings