You are here

public function TrackingHelper::trackReferencedEntityUpdate in Search API 8

Reacts to an entity being updated or deleted.

Determines whether this entity is indirectly referenced in any search index and, if so, marks all items referencing it as updated.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity that just got changed (updated or deleted).

bool $deleted: (optional) TRUE if the entity was deleted, FALSE if it was updated.

Overrides TrackingHelperInterface::trackReferencedEntityUpdate

See also

\Drupal\search_api\Datasource\DatasourceInterface::getAffectedItemsForEntityChange()

File

src/Utility/TrackingHelper.php, line 90

Class

TrackingHelper
Provides datasource-independent item change tracking functionality.

Namespace

Drupal\search_api\Utility

Code

public function trackReferencedEntityUpdate(EntityInterface $entity, bool $deleted = FALSE) {

  /** @var \Drupal\search_api\IndexInterface[] $indexes */
  $indexes = [];
  try {
    $indexes = $this->entityTypeManager
      ->getStorage('search_api_index')
      ->loadMultiple();
  } catch (InvalidPluginDefinitionException $e) {

    // Can't really happen, but play it safe to appease static code analysis.
  } catch (PluginNotFoundException $e) {

    // Can't really happen, but play it safe to appease static code analysis.
  }

  // Original entity, if available.
  $original = $deleted ? NULL : $entity->original ?? NULL;
  foreach ($indexes as $index) {

    // Map of foreign entity relations. Will get lazily populated as soon as
    // we actually need it.
    $map = NULL;
    foreach ($index
      ->getDatasources() as $datasource_id => $datasource) {
      if (!$datasource
        ->canContainEntityReferences()) {
        continue;
      }
      if ($map === NULL) {
        $map = $this
          ->getForeignEntityRelationsMap($index);

        // If there are no foreign entities in the index, no need to continue.
        if (!$map) {
          break 1;
        }
      }
      $item_ids = $datasource
        ->getAffectedItemsForEntityChange($entity, $map, $original);
      if (!empty($item_ids)) {
        $index
          ->trackItemsUpdated($datasource_id, $item_ids);
      }
    }
  }
}