You are here

public function EntityUsage::listSources in Entity Usage 8.3

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

Provide a list of all referencing source entities for a target entity.

Examples:

  • Return example 1:

[ 'node' => [ 123 => [ 'source_langcode' => 'en', 'source_vid' => '128', ], 124 => [ 'source_langcode' => 'en', 'source_vid' => '129', ], ], 'user' => [ 2 => [ 'source_langcode' => 'en', 'source_vid' => '2', ], ], ]

  • Return example 2:

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

Parameters

\Drupal\Core\Entity\EntityInterface $target_entity: A target entity.

bool $nest_results: (optional) Whether the results should be returned in a nested structure. Defaults to TRUE.

Return value

array A nested array with usage data. The first level is keyed by the type of the source entities, the second by the source id. The value of the second level contains all other information like the source language code or source revision ID. If $nest_results is FALSE, the returned array will be an indexed array where values are arrays containing all DB columns for the records.

Overrides EntityUsageInterface::listSources

File

src/EntityUsage.php, line 220

Class

EntityUsage
Defines the entity usage base class.

Namespace

Drupal\entity_usage

Code

public function listSources(EntityInterface $target_entity, $nest_results = TRUE) {

  // Entities can have string IDs. We support that by using different columns
  // on each case.
  $target_id_column = $this
    ->isInt($target_entity
    ->id()) ? 'target_id' : 'target_id_string';
  $result = $this->connection
    ->select($this->tableName, 'e')
    ->fields('e', [
    'source_id',
    'source_id_string',
    'source_type',
    'source_langcode',
    'source_vid',
  ])
    ->condition($target_id_column, $target_entity
    ->id())
    ->condition('target_type', $target_entity
    ->getEntityTypeId())
    ->orderBy('source_type')
    ->orderBy('source_id', 'DESC')
    ->orderBy('source_vid', 'DESC')
    ->orderBy('source_langcode')
    ->execute();
  $references = [];
  foreach ($result as $usage) {
    $source_id_value = !empty($usage->source_id) ? (string) $usage->source_id : (string) $usage->source_id_string;
    if ($nest_results) {
      $references[$usage->source_type][$source_id_value][] = [
        'source_langcode' => $usage->source_langcode,
        'source_vid' => $usage->source_vid,
      ];
    }
    else {
      $references[] = [
        'source_type' => $usage->source_type,
        'source_id' => $source_id_value,
        'source_langcode' => $usage->source_langcode,
        'source_vid' => $usage->source_vid,
      ];
    }
  }
  return $references;
}