Problem/Motivation
I noticed that an entity query using count()
returns a string instead of an int, which contradicts the return type of int|array
in \Drupal\Core\Entity\Query\Sql\Query.php
:
/**
* Executes the query and returns the result.
*
* @return int|array
* Returns the query result as entity IDs.
*/
protected function result() {
if ($this->count) {
return $this->sqlQuery->countQuery()->execute()->fetchField();
}
// Return a keyed array of results. The key is either the revision_id or
// the entity_id depending on whether the entity type supports revisions.
// The value is always the entity id.
return $this->sqlQuery->execute()->fetchAllKeyed();
}
Steps to reproduce
// Returns a string instead of an int.
$count = \Drupal::entityTypeManager()->getStorage('user')->getQuery()
->count()
->execute();
Proposed resolution
Cast the count result to an integer. This will be good in preparation for using return type hints in the future.
/**
* Executes the query and returns the result.
*
* @return int|array
* Returns the query result as entity IDs.
*/
protected function result() {
if ($this->count) {
return (int) $this->sqlQuery->countQuery()->execute()->fetchField();
}
// Return a keyed array of results. The key is either the revision_id or
// the entity_id depending on whether the entity type supports revisions.
// The value is always the entity id.
return $this->sqlQuery->execute()->fetchAllKeyed();
}
Remaining tasks
Find if a similar problem exists anywhere else in code?