Type hinting for Doctrine Collections

I'm wondering why I can't get the types correctly hinted for a doctrine collection. As I understand this should already work, doesn't it?

/** @var array<int, \My\Entity> $entityArray */
foreach ($entityArray as $arrayEntity) {
    // PhpStorm identifies the type of $arrayEntity as \My\Entity
}

/** @var \Doctrine\Common\Collections\Collection<int, \My\Entity> $entityCollection */
foreach ($entityCollection as $collectionEntity) {
    // PhpStorm can't identify the type of $collectionEntity
}

/** @psalm-var \Doctrine\Common\Collections\Collection<int, \My\Entity> $psalmEntityCollection */
foreach ($psalmEntityCollection as $psalmCollectionEntity) {
    // PhpStorm identifies the type of $psalmCollectionEntity as \Doctrine\Common\Collections\Collection
}

If I don't annotate the type at all, the type would be identified as `mixed`.

I don't know if I remember correctly, but didn't it already work in a version prior to 2020.3?

2
5 comments

I doubt that it was working in previous versions as some part of the Collections support was added only in 2020.3 EAP.

Please check this ticket and its relatives:

https://youtrack.jetbrains.com/issue/WI-43843

0
Avatar
Permanently deleted user

I know there was a lot of stuff added. That's why I think it is handled differently now.

Was it really just parsing it before (i.e. supporting the syntax) and just ignoring it? So in the end just like it does now? Unfortunately I don't have the option to roll back to 2020.2 on my machine to check.

I'm just asking myself what everyone else is doing as Doctrine is pretty commonly used. Since `@var Collection<int, Entity>` doesn't work (yet), the only option I see is `@var Collection<int, Entity>|Entity[]` or always having to `assert($entity instanceof Entity)` in a foreach or the like (which is what I want to avoid).

At least mixing the `array<x, y>` and `z[]` notations does work now (e.g. `array<string, SomeClass[]>`), that's a big plus!

0

Well, I don't know how it can help you but I have tested your examples on 2020.2.4 and all cases are detected as "mixed" there regardless of the annotation, so things were worse before.

0
Avatar
Permanently deleted user

Thanks for testing Vasiliy Yur. At least we now know I just remembered wrong (as suspected).

So we'll have to stick with the entity array union workaround until the collection generics are supported.

The ticket you linked above is marked "obsolete", https://youtrack.jetbrains.com/issue/WI-54573 is only for other language constructs like iterable or Generators, so https://youtrack.jetbrains.com/issue/WI-54573 is probably the one requesting this feature. Due to having 431 votes atm I suppose this is pretty high on your to do list (as I excepted this request to be).

0

Thank you for your reply.

Surely, you may always submit your own YouTrack report with a specific scenario that you would like to see supported.

0

Please sign in to leave a comment.