[PHP] How to provide type for foreach items in class implementing IteratorAggregate?

Answered

This is the scenario:    

$myObject = new MyClassImplementingIteratorAggregate();
foreach($myObject as $item){
$item->[ AUTOCOMPLETE HERE]
}

I was doing this in multiple ways inside PhpTypeProvider2, and was working fine but with almost every update in PhpStorm it stops working.

I can see there is a PhpTypeProvider4 now (not sure what is the difference)

But the problem with my current code is $item was a VariableDecl before, now that class does not even exist, I think it was replaced by VariableImpl but when I check VariableImpl::isDeclaration() for $item it returns false.     

Is there any recommended way to provide the correct type for foreach items?

Thanks !!

 

0
3 comments
Official comment

Using PhpTypeProvider4 right now should be fine. If you got working solution using PhpTypeProvider4, it will be enough to just switch to PhpTypeProvider4, com.jetbrains.php.lang.psi.resolve.types.PhpTypeProvider4#complete implementation can be just `return null;` in your case.

Hello. Actually, PhpStorm supposed to inherit types for foreach keys on IteratorAggregate inheritors by design, but don't this at the moment because of bug. Please vote for https://youtrack.jetbrains.com/issue/WI-9507/

0

Upvoted, but is not the same, I'm working with Magento, is really difficult for PhpStorm to guess the type of that. 
What I need is a good, efficient and safe way to give that type from PhpTypeProviderX, currently I have fixed it using PhpTypeProvider3 but would be nice to have some recommended way to do this from the official team

0

Please sign in to leave a comment.