You are here

public function EntityUsage::listUsage in Entity Usage 8

Same name and namespace in other branches
  1. 8.4 src/EntityUsage.php \Drupal\entity_usage\EntityUsage::listUsage()
  2. 8.2 src/EntityUsage.php \Drupal\entity_usage\EntityUsage::listUsage()

Determines where an entity is used.

Examples:

  • Return example 1:

[ 'node' => [ 123 => 1, 124 => 1, ], 'user' => [ 2 => 1, ], ]

  • Return example 2:

[ 'entity_reference' => [ 'node' => [...], 'user' => [...], ] ]

Parameters

\Drupal\Core\Entity\EntityInterface $entity: A target (referenced) entity.

bool $include_method: (optional) Whether the results must be wrapped into an additional array level, by the reference method. Defaults to FALSE.

Return value

array A nested array with usage data. The first level is keyed by the type of the referencing entities, the second by the referencing objects id. The value of the second level contains the usage count. Note that if $include_method is TRUE, the first level is keyed by the reference method, and the second level will continue as explained above.

Overrides EntityUsageInterface::listUsage

File

src/EntityUsage.php, line 148

Class

EntityUsage
Defines the entity usage base class.

Namespace

Drupal\entity_usage

Code

public function listUsage(EntityInterface $entity, $include_method = FALSE) {
  $result = $this->connection
    ->select($this->tableName, 'e')
    ->fields('e', [
    're_id',
    're_type',
    'method',
    'count',
  ])
    ->condition('t_id', $entity
    ->id())
    ->condition('t_type', $entity
    ->getEntityTypeId())
    ->condition('count', 0, '>')
    ->execute();
  $references = [];
  foreach ($result as $usage) {
    if ($include_method) {
      $references[$usage->method][$usage->re_type][$usage->re_id] = $usage->count;
    }
    else {
      $count = $usage->count;

      // If there were previous usages recorded for this same pair of entities
      // (with different methods), sum on the top of it.
      if (!empty($references[$usage->re_type][$usage->re_id])) {
        $count += $references[$usage->re_type][$usage->re_id];
      }
      $references[$usage->re_type][$usage->re_id] = $count;
    }
  }
  return $references;
}