You are here

function entity_language_fallback_entity_update in Entity Language Fallback 8

Implements hook_entity_update().

search_api_entity_update() can only update items that are in ContentEntity datasources.

See also

search_api_entity_update().

File

./entity_language_fallback.module, line 126
Add fallback languages to entities.

Code

function entity_language_fallback_entity_update(EntityInterface $entity) {
  if (!\Drupal::moduleHandler()
    ->moduleExists('search_api')) {
    return;
  }

  // Check if the entity is a content entity.
  if (!$entity instanceof ContentEntityInterface || $entity->search_api_skip_tracking) {
    return;
  }
  $indexes = ContentEntityFallback::getIndexesForEntity($entity);
  if (!$indexes) {
    return;
  }

  /** @var \Drupal\entity_language_fallback\FallbackControllerInterface $fallback_controller */
  static $fallback_controller;
  if (!isset($fallback_controller)) {
    $fallback_controller = \Drupal::service('language_fallback.controller');
  }

  // Compare old and new languages for the entity to identify inserted,
  // updated and deleted translations (and, therefore, search items).
  $entity_id = $entity
    ->id();
  $inserted_item_ids = [];
  $updated_item_ids = $fallback_controller
    ->getTranslations($entity);
  $deleted_item_ids = [];
  $old_translations = $fallback_controller
    ->getTranslations($entity->original);
  foreach ($old_translations as $langcode => $language) {
    if (!isset($updated_item_ids[$langcode])) {
      $deleted_item_ids[] = $langcode;
    }
  }
  foreach ($updated_item_ids as $langcode => $language) {
    if (!isset($old_translations[$langcode])) {
      unset($updated_item_ids[$langcode]);
      $inserted_item_ids[] = $langcode;
    }
  }
  $datasource_id = 'entity_language_fallback:' . $entity
    ->getEntityTypeId();
  $combine_id = function ($langcode) use ($entity_id) {
    return $entity_id . ':' . $langcode;
  };
  $inserted_item_ids = array_map($combine_id, $inserted_item_ids);
  $updated_item_ids = array_map($combine_id, array_keys($updated_item_ids));
  $deleted_item_ids = array_map($combine_id, $deleted_item_ids);
  foreach ($indexes as $index) {
    if ($inserted_item_ids) {
      $filtered_item_ids = ContentEntityFallback::filterValidItemIds($index, $datasource_id, $inserted_item_ids);
      $index
        ->trackItemsInserted($datasource_id, $filtered_item_ids);
    }
    if ($updated_item_ids) {
      $index
        ->trackItemsUpdated($datasource_id, $updated_item_ids);
    }
    if ($deleted_item_ids) {
      $index
        ->trackItemsDeleted($datasource_id, $deleted_item_ids);
    }
  }
}