6

I'm often frustrated by entityTypeManager because when I load entities, the typehint for the return value of the load methods is EntityInterface, but I want it to be a more specific interface (which I know it will be because I am loading a specific entity type with getStorage).

So, for example, consider this code adapted from the Flag module:

  /**
   * Loads flagging entities given their IDs.
   *
   * @param int[] $ids
   *   The flagging IDs.
   *
   * @return \Drupal\flag\FlaggingInterface[]
   *   An array of flaggings.
   */
  private function getFlaggingsByIds(array $ids): array {
    return $this->entityTypeManager->getStorage('flagging')->loadMultiple($ids);
  }

PHPStan points out that there is a return type mismatch here because the doc comment is FlaggingInterface[] but loadMultiple() resolves to EntityInterface[].

I can fix this by rewriting as follows:

$ids = $this->entityTypeManager->getStorage('flagging')->loadMultiple($ids);
/** @var \Drupal\flag\FlagInterface[] $ids */
return $ids;

But then I have to introduce an extra variable just to get the correct typehint. Is there a more efficient way to override the typehint in this kind of case?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.