Quantcast
Channel: Issues for Drupal core
Viewing all articles
Browse latest Browse all 294437

Entity count query returns a string instead of int

$
0
0

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?

User interface changes

API changes

Data model changes

Release notes snippet


Viewing all articles
Browse latest Browse all 294437

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>