You are here

public function CiviEntityStorage::countFieldData in CiviCRM Entity 8.3

Throws

\Drupal\Core\Entity\Sql\SqlContentEntityStorageException

Overrides SqlContentEntityStorage::countFieldData

File

src/CiviEntityStorage.php, line 252

Class

CiviEntityStorage
Defines entity class for external CiviCRM entities.

Namespace

Drupal\civicrm_entity

Code

public function countFieldData($storage_definition, $as_bool = FALSE) {

  // The table mapping contains stale data during a request when a field
  // storage definition is added, so bypass the internal storage definitions
  // and fetch the table mapping using the passed in storage definition.
  // @todo Fix this in https://www.drupal.org/node/2705205.
  $table_mapping = $this
    ->getTableMapping();
  if ($table_mapping
    ->requiresDedicatedTableStorage($storage_definition)) {
    $is_deleted = $storage_definition instanceof FieldStorageConfigInterface && $storage_definition
      ->isDeleted();
    $table_name = $table_mapping
      ->getDedicatedDataTableName($storage_definition, $is_deleted);
    $query = $this->database
      ->select($table_name, 't');
    $or = $query
      ->orConditionGroup();
    foreach ($storage_definition
      ->getColumns() as $column_name => $data) {
      $or
        ->isNotNull($table_mapping
        ->getFieldColumnName($storage_definition, $column_name));
    }
    $query
      ->condition($or);
    if (!$as_bool) {
      $query
        ->fields('t', [
        'entity_id',
      ])
        ->distinct(TRUE);
    }
  }

  // @todo Find a way to count field data also for fields having custom
  //   storage. See https://www.drupal.org/node/2337753.
  $count = 0;
  if (isset($query)) {

    // If we are performing the query just to check if the field has data
    // limit the number of rows.
    if ($as_bool) {
      $query
        ->range(0, 1)
        ->addExpression('1');
    }
    else {

      // Otherwise count the number of rows.
      $query = $query
        ->countQuery();
    }
    $count = $query
      ->execute()
      ->fetchField();
  }
  return $as_bool ? (bool) $count : (int) $count;
}