idea-php-symfony2-plugin icon indicating copy to clipboard operation
idea-php-symfony2-plugin copied to clipboard

Typehint problem for getContainer()->get()

Open yack01 opened this issue 4 years ago • 10 comments

Idea/Symfony can't recognize returned type for Symfony's service container from Symfony\Bundle\FrameworkBundle\Test\KernelTestCase::getContainer()->get().

I get the next message: Incompatible types: Expected property of type '\MyNameSpace\MyEntityInterface', '\MyNameSpace\MyEntity|null|object' provided

Code example:

 self::bootKernel();
 $this->storage = self::getContainer()->get('my_service_name');

PhpStorm screenshot: image

yack01 avatar May 06 '21 14:05 yack01

I have the same problem. really sad, as this works fine in the past

mitelg avatar Feb 11 '22 07:02 mitelg

Same issue. The only way to get autocompletion is to annotate with `/** @var ... **/.

In the meantime, tried with the .phpstorm.meta.php below, but without success:

<?php

namespace PHPSTORM_META {
    override(\Psr\Container\ContainerInterface::get(0), map([
        '' => '@',
    ]));
}

darthf1 avatar Jul 05 '22 07:07 darthf1

Suppressing is always a bad idea and result in potential code smell.

I'd say only a explicit overload method in ContainerInterface like getOrFail(...), resolve(...) or introspect(...) in Symfony itself may solve this problem. However, this would imply that get fails silently and returns null when reference is missing (Breaking Change).

Narrow types won't work with the current implementation of ContainerInterface::get regardless..


Infering the return type from the input parameter would be the next big step as PHP 8 enhances type safety. Psalm has already solved this problem with method annotations like this:

/**
* @psalm-template RealInstanceType of object
* @psalm-param class-string<RealInstanceType> $id
* @psalm-return RealInstanceType
*/

Maybe its possible to provide a similar behaviour by this plugin?

leptoquark1 avatar Apr 23 '23 02:04 leptoquark1

One of the ways to solve this problem is: create a file .phpstorm.meta.php and paste following code

<?php
namespace PHPSTORM_META {
    use Psr\Container\ContainerInterface;
    override(ContainerInterface::get(0), type(0));
}

HiLevel16 avatar May 09 '24 16:05 HiLevel16

@HiLevel16 that does not work for me

mitelg avatar May 13 '24 14:05 mitelg

@mitelg Do you use phpstorm? What version? If your version is under 02-2019, this feature won't work Also take a view to your ::getContainer() function's return value. It must be ContainerInterface

HiLevel16 avatar May 13 '24 14:05 HiLevel16

There are conflicting type providers. On a non PhpStorm (Intellij) its working. Need to find a workaround for this.

image

Haehnchen avatar May 13 '24 16:05 Haehnchen