phpstan-drupal icon indicating copy to clipboard operation
phpstan-drupal copied to clipboard

Extension to refine hook parameter types

Open mglaman opened this issue 2 years ago • 4 comments

Feature request

Classic example of failed deprecation discovery due to level 0 and undefined methods: #210. I wonder if we could fix that using a type specifying extension.

function mymodule_node_insert(EntityInterface $node) {
  
 if ($node->getRevisionAuthor()) {
   // Missing deprecation warning!
 }
  
}

The method matches hook_ENTITY_TYPE_{op}. So we can narrow the type of EntityInterface to NodeInterface. However this should only run if the parameter is the root EntityInterface interface.

mglaman avatar Apr 25 '23 21:04 mglaman

I think its better to fix those error with a custom rule and recommend to use a more precise type e.g. NodeInterface in this example. It will improve the code and DX in the editor.

webflo avatar May 13 '23 20:05 webflo

Right now it does report an error, and everyone complains that they shouldn't because of coding standards or who knows what. This feature request is me caving to constantly having to explain.

Maybe it's something that can be explained in the docs https://www.drupal.org/docs/develop/development-tools/phpstan and in the entity hook API docs.

mglaman avatar May 13 '23 20:05 mglaman

It is already on https://www.drupal.org/docs/develop/development-tools/phpstan/fixing-reports-of-undefined-methods

webflo avatar May 13 '23 21:05 webflo

💡 okay I think it may be needs a more specific title about hook parameters beyond just that example.

mglaman avatar May 13 '23 23:05 mglaman