idea-php-symfony2-plugin
idea-php-symfony2-plugin copied to clipboard
Typehint problem for getContainer()->get()
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:

I have the same problem. really sad, as this works fine in the past
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([
'' => '@',
]));
}
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?
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 that does not work for me
@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
There are conflicting type providers. On a non PhpStorm (Intellij) its working. Need to find a workaround for this.