I'm running PHPStan in my project on level 9 and I'm closing in on zero errors now. One problem I can't find a solution for though is in the CRUD part of my project.
With >50 complex entities that require permissions, have relations etc. of course I could not write the CRUD part n-times, repeating the same logic and templates again and again. Instead I have a central CrudController and the name of an entity as well as the ID of a specific entry that e.g. needs to be updated are part of the URL:
.../crud/[Entity]/[ID]
such as .../crud/Article/123
The controller action (Symfony here = the class method) then takes the name of the entity in variable $entity to load the specific entry with the ID in $id. So instead of
$entry = new Article(...);
I have to load the correct entity like this:
$entry = new $entity(...);
Everything in my CRUD already works. The issue here is that PHPStan doesn't understand the type of the object that is being returned. I've tried various ways like
/** @var $entity $entry */
above the declaration of variable $entry but to no avail. PHPStan just throws errors like
PHPDoc tag @var contains unknown class ...
or PHPDoc tag @var has invalid value...
Here's a very basic version of this issue in a playground: https://phpstan.org/r/d9cb71bc-f2c5-4387-a3d6-841656824d41
Without something like @var anything else that happens with $entry then throws errors, e.g.:
$id = $entry->getId();
throws
Call to undefined method object::getId().
I've read about generics / templates etc. in the documentation but that wasn't successful. I can't change the entities or their PHPDoc comments. So I guess I have to rely on @var above the variable declaration. But I also can't add all possible entity names like so:
/** @var Article|Blog|Statistic|... $entry */
So is there a clean way to tell PHPDoc that the object type is dynamic and based on $entity?