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

Viewed 158

There is a method call expression:

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

where setUser is declared as

public function setUser(UserAccount $user): self

$this->em->getReference being a Doctrines's entity manager method returns object|null.

So PhpStorm marks this call as mismatching argument-parameter types.

I surely can split it into 2 statements and type it:

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

But may be there is a way to do that inline?

2 Answers

Unfortunately there is no such language feature and you can rely only on PHPDoc or Symfony plugin for PHPStorm.

Since Symfony plugin claims only next features:

  • QueryBuilder support, including chaining and nested methods
  • References and TypeProvider for doctrine getRepository
  • TypeProvider for EntityRepository::find/findOneBy/findAll/findBy
  • Field and relations resolving and annotation and yaml

you can use find*() methods or PHPDoc solution shown above. Please keep in mind, according to possibility to return null by Doctrine's methods the plugin way still show you an warning about passing null as not nullable argument.

There is a Github issue about getReference() resolving.

I'm pretty sure it's possible with what they call PHPStorm advanced metadata. As far as I understand you want something like this (you may need to experiment)

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