You are here

class SearchService 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

Expose synonyms of referenced entities to core Search index.

Hierarchy

Expanded class hierarchy of SearchService

1 string reference to 'SearchService'
synonyms_search.services.yml in synonyms_search/synonyms_search.services.yml
synonyms_search/synonyms_search.services.yml
1 service uses SearchService
synonyms.behavior.search in synonyms_search/synonyms_search.services.yml
Drupal\synonyms_search\SynonymsService\Behavior\SearchService

File

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

Namespace

Drupal\synonyms_search\SynonymsService\Behavior
View source
class SearchService implements SynonymsBehaviorInterface {
  use StringTranslationTrait;

  /**
   * Behavior name this class represents.
   *
   * @var string
   */
  const BEHAVIOR = 'synonyms.behavior.search';

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The synonyms behavior service.
   *
   * @var \Drupal\synonyms\SynonymsService\BehaviorService
   */
  protected $behaviorService;

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * The time.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * SearchService constructor.
   */
  public function __construct(EntityFieldManagerInterface $entity_field_manager, EntityTypeManagerInterface $entity_type_manager, BehaviorService $behavior_service, Connection $database, TimeInterface $time) {
    $this->entityFieldManager = $entity_field_manager;
    $this->entityTypeManager = $entity_type_manager;
    $this->behaviorService = $behavior_service;
    $this->database = $database;
    $this->time = $time;
  }

  /**
   * Implementation of hook_entity_view().
   */
  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']);
    }
  }

  /**
   * Mark all search index dependent on a given entity for reindexing.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   Entity whose dependent search index should be marked for reindexing.
   */
  public function entityMarkForReindex(ContentEntityInterface $entity) {
    $this
      ->entityMarkForReindexMultiple([
      $entity
        ->id(),
    ], $entity
      ->getEntityTypeId());
  }

  /**
   * Mark all search index dependent on given entities for reindexing.
   *
   * @param array $entity_ids
   *   Entity IDs whose dependent search index should be marked for reindexing.
   * @param string $entity_type
   *   Entity type of the give entity IDs.
   */
  public function entityMarkForReindexMultiple(array $entity_ids, $entity_type) {
    if (empty($entity_ids)) {
      return;
    }
    $map = $this->entityFieldManager
      ->getFieldMapByFieldType('entity_reference');
    foreach ($map as $host_entity_type => $fields) {
      foreach ($fields as $field_name => $field_info) {
        $field = FieldStorageConfig::loadByName($host_entity_type, $field_name);
        if ($field && $field
          ->getSetting('target_type') == $entity_type) {
          $query = $this->entityTypeManager
            ->getStorage($host_entity_type)
            ->getQuery();
          $query
            ->condition($field_name, $entity_ids, 'IN');
          $result = $query
            ->execute();

          // For the sake of performance we do a direct query on the
          // {search_dataset} table instead of using search_mark_for_reindex()
          // function.
          // @todo Is there any smarter way to generate search type rather then
          // adding suffix of '_search'?
          if (!empty($result)) {
            $this->database
              ->update('search_dataset')
              ->fields([
              'reindex' => $this->time
                ->getRequestTime(),
            ])
              ->condition('reindex', 0)
              ->condition('type', $host_entity_type . '_search')
              ->condition('sid', array_values($result), 'IN')
              ->execute();
          }
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    return $this
      ->t('Search');
  }

  /**
   * Retrieve a list of synonyms from a given entity.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   The given entity.
   *
   * @return string[]
   *   A list of synonyms of a given entity
   */
  protected function getEntitySynonyms(ContentEntityInterface $entity) {
    $synonyms = [];
    foreach ($this->behaviorService
      ->getSynonymConfigEntities(self::BEHAVIOR, $entity
      ->getEntityTypeId(), $entity
      ->bundle()) as $synonym_config) {
      $synonyms = array_merge($synonyms, $synonym_config
        ->getProviderPluginInstance()
        ->getSynonyms($entity));
    }
    return $synonyms;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
SearchService::$behaviorService protected property The synonyms behavior service.
SearchService::$database protected property The database connection.
SearchService::$entityFieldManager protected property The entity field manager.
SearchService::$entityTypeManager protected property The entity type manager.
SearchService::$time protected property The time.
SearchService::BEHAVIOR constant Behavior name this class represents.
SearchService::entityMarkForReindex public function Mark all search index dependent on a given entity for reindexing.
SearchService::entityMarkForReindexMultiple public function Mark all search index dependent on given entities for reindexing.
SearchService::entityView public function Implementation of hook_entity_view().
SearchService::getEntitySynonyms protected function Retrieve a list of synonyms from a given entity.
SearchService::getTitle public function Get human readable title of this behavior. Overrides SynonymsBehaviorInterface::getTitle
SearchService::__construct public function SearchService constructor.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.