Fixing reports of undefined methods

Last updated on
7 January 2022

This documentation needs work. See "Help improve this page" in the sidebar.

When working with entities, often times PHPStan only knows the object as EntityInterface and not the actual entity. In your code, whenever working with an entity, make sure to type hint using one of the following ways:

// Using asserts – great for development, as it'll throw an error at runtime if wrong (ie: null or wrong object type.)
$foo = $node->get('some_entity_reference')->entity;
assert($foo instanceof \Drupal\taxonomy_term\TermInterface);


// Use doc type hinting. 
/** @var \Drupal\taxonomy_term\TermInterface $foo */
$foo = $node->get('some_entity_reference')->entity;

// Put your code in an if statement
$foo = $node->get('some_entity_reference')->entity;
if ($foo instanceof \Drupal\taxonomy_term\TermInterface) {

}

If you are working with hooks, just update the parameter type hint.

mymodule_node_insert(NodeInterface $node)

Help improve this page

Page status: Needs work

You can: