2

我尝试使用 PHPStan 改进我的代码。我已经安装:

这是我的phpstan.neon:

includes:
  - vendor/phpstan/phpstan/conf/config.levelmax.neon
  - vendor/phpstan/phpstan-symfony/extension.neon
  - vendor/phpstan/phpstan-doctrine/extension.neon
  - vendor/phpstan/phpstan-doctrine/rules.neon
  - vendor/phpstan/phpstan-phpunit/extension.neon
  - vendor/phpstan/phpstan-phpunit/rules.neon
parameters:
  paths:
    - %currentWorkingDirectory%/src
    - %currentWorkingDirectory%/tests
  symfony:
    container_xml_path: '%currentWorkingDirectory%/var/cache/dev/srcApp_KernelDevDebugContainer.xml'
  autoload_directories:
    - %currentWorkingDirectory%/tests

我还测试了调用下一个函数:

$kernel = static::bootKernel();
$doctrine = $kernel->getContainer()->get('doctrine');
$doctrine->getManager()->getConfiguration();
$doctrine->getManager()->getEventManager();

PHPStan 对此抱怨:

Call to an undefined method Doctrine\Common\Persistence\ObjectManager::getConfiguration().
Call to an undefined method Doctrine\Common\Persistence\ObjectManager::getEventManager().

我研究过$doctrine->getManager()我有Doctrine\ORM\EntityManagerInterface那个扩展Doctrine\Common\Persistence\ObjectManager,但 PHPStan 认为我有Doctrine\Common\Persistence\ObjectManager

如何告诉 PHPStan 那$doctrine->getManager()Doctrine\ORM\EntityManagerInterface

4

1 回答 1

2

您可以:

  1. 添加内联 PHPDoc(可在任何地方使用):
/** @var \Doctrine\ORM\EntityManagerInterface */
$doctrine = $kernel->getContainer()->get('doctrine');
  1. 使用断言(仅在测试中有效):
$doctrine = $kernel->getContainer()->get('doctrine');
self::assertInstanceOf(EntityManagerInterface::class, $doctrine);
于 2019-09-14T17:25:39.647 回答