我尝试用PHPStan改进我的代码。我已经安装了:
- PHPStan
- PHPStan 的学说扩展
- PHPStan PHPUnit 扩展和规则
- PHPStan Symfony 框架扩展和规则
这是我的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 DoctrineCommonPersistenceObjectManager::getConfiguration().
Call to an undefined method DoctrineCommonPersistenceObjectManager::getEventManager().
我研究了那个$doctrine->getManager()
我有DoctrineORMEntityManagerInterface
扩展DoctrineCommonPersistenceObjectManager
但 PHPStan 认为我有DoctrineCommonPersistenceObjectManager
如何告诉 PHPStan $doctrine->getManager()
是DoctrineORMEntityManagerInterface
?
您可以:
- 添加一个内联 PHPDoc(可在任何地方使用(:
/** @var DoctrineORMEntityManagerInterface */
$doctrine = $kernel->getContainer()->get('doctrine');
- 使用断言(仅适用于测试(:
$doctrine = $kernel->getContainer()->get('doctrine');
self::assertInstanceOf(EntityManagerInterface::class, $doctrine);