phpstan-symfony icon indicating copy to clipboard operation
phpstan-symfony copied to clipboard

False positive with Container::get not nullable

Open noemi-salaun opened this issue 5 years ago • 3 comments

Symfony\Component\DependencyInjection\ContainerInterface::get() can return null when using ContainerInterface::NULL_ON_INVALID_REFERENCE

$stack = $container->get('request_stack', ContainerInterface::NULL_ON_INVALID_REFERENCE);
if (null === $stack) {
    return null;
}

Strict comparison using === between null and Symfony\Component\HttpFoundation\RequestStack will always evaluate to false.

noemi-salaun avatar Feb 04 '20 18:02 noemi-salaun

I am actually thinking about straight up disallowing the get on containers. What are your thoughts about that?

Otherwise, this one might currrently be tough to fix. I have some ideas, but it would possibly require some major refactoring, and I am not sure about the results. Plus I am currently swamped with other work.

So for now, please just mark the error as ignored, and I promise to look at it as soon as I have some spare time. 😊 Thanks.

lookyman avatar Feb 04 '20 20:02 lookyman

I am actually thinking about straight up disallowing the get on containers. What are your thoughts about that?

I think it's a little too opinionated to simply disallow its usage. Maybe in a package like phpstan/phpstan-strict-rules but not as default in this package.

noemi-salaun avatar Feb 05 '20 18:02 noemi-salaun

There is an opposite problem too. In case containerXmlPath is not specified, it will claim return type is nullable. We have these kind of tests a lot

class FooTest extends \Symfony\Bundle\FrameworkBundle\Test\KernelTestCase
{
    private Foo $foo;

    protected function setUp(): void
    {
        $this->foo = $this->getContainer()->get(Foo::class);
    }

but phpstan complains here with

Property FooTest::$foo (Foo) does not accept object|null.

ostrolucky avatar Dec 03 '22 12:12 ostrolucky