是否可以在 PHPDoc 的调用方为参数指定显式类型

Is it possible to specify explicit type for the parameter in a caller side for PHPDoc

有一个方法调用表达式:

$session->setUser($this->em->getReference(UserAccount::class, $ownerId));

其中 setUser 声明为

public function setUser(UserAccount $user): self

$this->em->getReference 是 Doctrines 的实体管理器方法 returns object|null.

因此 PhpStorm 将此调用标记为不匹配的参数类型。

我当然可以将其拆分为 2 个语句并键入:

/** @var UserAccount $userAccount */
$userAccount = $this->em->getReference(UserAccount::class, $ownerId);
$session->setUser($userAccount);

但是可能有一种内联的方法吗?

不幸的是,没有这样的语言功能,您只能依赖 PHPDoc 或 PHPStorm 的 Symfony 插件。

因为 Symfony plugin claims 只有下一个特征:

  • QueryBuilder 支持,包括链接和嵌套方法
  • 学说 getRepository 的引用和 TypeProvider
  • EntityRepository 的 TypeProvider::find/findOneBy/findAll/findBy
  • 字段和关系解析以及注释和 yaml

您可以使用 find*() 方法或上面显示的 PHPDoc 解决方案。请记住,根据 Doctrine 的方法 return null 的可能性,插件方式仍然会向您显示有关将 null 作为不可空参数传递的警告。

关于 getReference() resolving 有一个 Github 问题。

我很确定他们所说的 PHPStorm advanced metadata 是可能的。据我了解你想要这样的东西(你可能需要试验)

override(\Doctrine\ORM\EntityManagerInterface::getReference(0), map([
    '' => '@'
]))