sascha-egerer / phpstan-typo3

TYPO3 CMS class reflection extension for PHPStan & framework-specific rules
MIT License
42 stars 22 forks source link

Generic support for Psr\EventDispatcher\EventDispatcherInterface (psr/event-dispatcher) #135

Closed bfzgaier closed 1 year ago

bfzgaier commented 1 year ago

Hello,

I know that psr/event-dispatcher is a 3-party dependency for TYPO3, so it is fine if it is out of scope.

Could you add generic support for Psr\EventDispatcher\EventDispatcherInterface. Let's say you have code like this:

$event = $eventDispatcher->dispatch(new SomeEvent());
$event->someFunction():

PHPStan can not resolve the real type of $event, therefore it will trigger an Call to an undefined method object::someFunction() error.

The easy solution is to add an annotation for $event, but you will need to do it every time you dispatch an event. The possibility to omit the annotation would also allow for dropping the intermediate variable $event and combining it into one line.

Thank you for your effort and this ruleset.

sabbelasichon commented 1 year ago

What you could do in order to fix it right away, is to add a stub file somewhere in your project directory with the following content:

<?php

namespace Psr\EventDispatcher;

interface EventDispatcherInterface
{
    /**
     * @template TEvent of object
     * @param TEvent $event
     *
     * @return TEvent
     */
    public function dispatch(object $event);
}

You also have to include the stub file in your phpstan.neon file https://phpstan.org/user-guide/stub-files

sabbelasichon commented 1 year ago

@bfzgaier But maybe it is useful to add such a stub file in this package. I will try to discuss it with @sascha-egerer

sabbelasichon commented 1 year ago

@sascha-egerer What do you think? Should we add such a stub file in this package here?