You are here

public function SearchService::entityView in Synonyms 8

Same name and namespace in other branches
  1. 2.0.x modules/synonyms_search/src/SynonymsService/Behavior/SearchService.php \Drupal\synonyms_search\SynonymsService\Behavior\SearchService::entityView()

Implementation of hook_entity_view().

File

synonyms_search/src/SynonymsService/Behavior/SearchService.php, line 83

Class

SearchService
Expose synonyms of referenced entities to core Search index.

Namespace

Drupal\synonyms_search\SynonymsService\Behavior

Code

public function entityView(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($entity instanceof ContentEntityInterface && $view_mode == 'search_index') {
    $synonyms = [];
    $cacheable_metadata = new CacheableMetadata();
    $entity_references = array_filter($this->entityFieldManager
      ->getFieldDefinitions($entity
      ->getEntityTypeId(), $entity
      ->bundle()), function ($item) {
      if ($item
        ->getType() == 'entity_reference') {
        $target_entity_type = $this->entityTypeManager
          ->getDefinition($item
          ->getSetting('target_type'));
        return $target_entity_type instanceof ContentEntityTypeInterface;
      }
      return FALSE;
    });
    foreach ($entity_references as $entity_reference) {
      foreach ($entity
        ->get($entity_reference
        ->getName())
        ->referencedEntities() as $target_entity) {
        $synonyms = array_merge($synonyms, $this
          ->getEntitySynonyms($target_entity));
        $cacheable_metadata
          ->addCacheableDependency($target_entity);

        // Depend on the synonyms configs for this entity type + bundle.
        $cacheable_metadata
          ->addCacheTags([
          Synonym::cacheTagConstruct(self::BEHAVIOR, $target_entity
            ->getEntityTypeId(), $target_entity
            ->bundle()),
        ]);
      }
    }
    $build['synonyms_search'] = [
      '#markup' => implode(', ', $synonyms),
    ];
    $cacheable_metadata
      ->applyTo($build['synonyms_search']);
  }
}