You are here

protected function AddHierarchy::addHierarchyValues in Search API 8

Adds all ancestors' IDs of the given entity to the given field.

Parameters

string $entityTypeId: The entity type ID.

mixed $entityId: The ID of the entity for which ancestors should be found.

string $property: The name of the property on the entity type which contains the references to the parent entities.

\Drupal\search_api\Item\FieldInterface $field: The field to which values should be added.

Throws

\Drupal\Component\Plugin\Exception\PluginNotFoundException Thrown if a referenced entity type does not exist.

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException Thrown if a referenced entity's storage handler couldn't be loaded.

1 call to AddHierarchy::addHierarchyValues()
AddHierarchy::preprocessIndexItems in src/Plugin/search_api/processor/AddHierarchy.php
Preprocesses search items for indexing.

File

src/Plugin/search_api/processor/AddHierarchy.php, line 321

Class

AddHierarchy
Adds all ancestors' IDs to a hierarchical field.

Namespace

Drupal\search_api\Plugin\search_api\processor

Code

protected function addHierarchyValues($entityTypeId, $entityId, $property, FieldInterface $field) {
  if ("{$entityTypeId}-{$property}" == 'taxonomy_term-parent') {

    /** @var \Drupal\taxonomy\TermStorageInterface $entity_storage */
    $entity_storage = $this
      ->getEntityTypeManager()
      ->getStorage('taxonomy_term');
    $parents = [];
    foreach ($entity_storage
      ->loadParents($entityId) as $term) {
      $parents[] = $term
        ->id();
    }
  }
  else {
    $entity = $this
      ->getEntityTypeManager()
      ->getStorage($entityTypeId)
      ->load($entityId);
    $parents = [];
    if ($entity instanceof ContentEntityInterface) {
      try {
        foreach ($entity
          ->get($property) as $data) {
          $values = static::getFieldsHelper()
            ->extractFieldValues($data);
          $parents = array_merge($parents, $values);
        }
      } catch (\InvalidArgumentException $e) {

        // Might happen, for example, if the property only exists on a certain
        // bundle, and this entity has the wrong one.
      }
    }
  }
  foreach ($parents as $parent) {
    if (!in_array($parent, $field
      ->getValues())) {
      $field
        ->addValue($parent);
      $this
        ->addHierarchyValues($entityTypeId, $parent, $property, $field);
    }
  }
}