You are here

public function EmbedBase::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/EmbedBase.php, line 91

Class

EmbedBase
Base class for plugins tracking usage in entities embedded in WYSIWYG 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);
  }
  $current_uuids = [];
  foreach ($translations as $translation) {
    $current_uuids += $this
      ->getEmbeddedEntitiesByField($translation, TRUE);
  }
  $original_uuids = [];
  foreach ($originals as $original) {
    $original_uuids += $this
      ->getEmbeddedEntitiesByField($original, TRUE);
  }
  $added_uuids = array_diff_key($current_uuids, $original_uuids);
  $removed_uuids = array_diff_key($original_uuids, $current_uuids);
  foreach ($added_uuids as $uuid => $type) {
    $this
      ->incrementEmbeddedUsage($entity, $type, $uuid);
  }
  foreach ($removed_uuids as $uuid => $type) {
    $this
      ->decrementEmbeddedUsage($entity, $type, $uuid);
  }
}