You are here

public function EntityReference::trackOnEntityUpdate in Entity Usage 8

Track usage updates on the edition of entities.

Parameters

\Drupal\Core\Entity\ContentEntityInterface $entity: The entity we are dealing with.

Overrides EntityUsageTrackBase::trackOnEntityUpdate

File

src/Plugin/EntityUsage/Track/EntityReference.php, line 100

Class

EntityReference
Tracks usage of entities related in entity_reference fields.

Namespace

Drupal\entity_usage\Plugin\EntityUsage\Track

Code

public function trackOnEntityUpdate(ContentEntityInterface $entity) {

  // The assumption here is that an entity that is referenced by any
  // translation of another entity should be tracked, and only once
  // (regardless if many translations point to the same entity). So the
  // process to identify them is quite simple: we build a list of all entity
  // ids referenced before the update by all translations (original included),
  // and compare it with the list of ids referenced by all translations after
  // the update.
  $translations = [];
  $originals = [];
  $languages = $entity
    ->getTranslationLanguages();
  foreach ($languages as $langcode => $language) {
    if (!$entity
      ->hasTranslation($langcode)) {
      continue;
    }
    $translations[] = $entity
      ->getTranslation($langcode);
    if (!$entity->original
      ->hasTranslation($langcode)) {
      continue;
    }
    $originals[] = $entity->original
      ->getTranslation($langcode);
  }
  foreach ($this
    ->entityReferenceFieldsAvailable($entity) as $field_name) {
    $current_target_ids = [];
    foreach ($translations as $translation) {
      if (!$translation->{$field_name}
        ->isEmpty()) {
        foreach ($translation->{$field_name} as $field_item) {
          $current_target_ids[] = $field_item->target_id;
        }
      }
    }
    $original_target_ids = [];
    foreach ($originals as $original) {
      if (!$original->{$field_name}
        ->isEmpty()) {
        foreach ($original->{$field_name} as $field_item) {
          $original_target_ids[] = $field_item->target_id;
        }
      }
    }

    // If more than one translation references the same target entity, we
    // record only one usage.
    $original_target_ids = array_unique($original_target_ids);
    $current_target_ids = array_unique($current_target_ids);
    $added_ids = array_diff($current_target_ids, $original_target_ids);
    $removed_ids = array_diff($original_target_ids, $current_target_ids);
    foreach ($added_ids as $id) {
      $this
        ->incrementEntityReferenceUsage($entity, $field_name, $id);
    }
    foreach ($removed_ids as $id) {
      $this
        ->decrementEntityReferenceUsage($entity, $field_name, $id);
    }
  }
}