You are here

public function EntityGetBySynonym::entityGetBySynonym in Synonyms 8

Try finding entities by their name or synonym.

Parameters

\Drupal\Core\Entity\EntityTypeInterface $entity_type: What entity type is being searched.

string $name: The look up keyword (the supposed name or synonym).

string $bundle: Optionally limit the search within a specific bundle name of the provided entity type.

Return value

array IDs of the looked up entities. If such entity is not found, an empty array is returned.

File

src/SynonymsService/EntityGetBySynonym.php, line 52

Class

EntityGetBySynonym
Service to look up an entity by its name or synonym.

Namespace

Drupal\synonyms\SynonymsService

Code

public function entityGetBySynonym(EntityTypeInterface $entity_type, $name, $bundle = NULL) {
  if ($entity_type
    ->id() == 'user' || $entity_type
    ->hasKey('label')) {
    $label_column = $entity_type
      ->id() == 'user' ? 'name' : $entity_type
      ->getKey('label');
    $query = $this->entityTypeManager
      ->getStorage($entity_type
      ->id())
      ->getQuery();
    $query
      ->condition($label_column, $name);
    if ($entity_type
      ->hasKey('bundle') && $bundle) {
      $query
        ->condition($entity_type
        ->getKey('bundle'), $bundle);
    }
    $result = $query
      ->execute();
    $result = reset($result);
    if ($result) {
      return $result;
    }
  }
  $condition = new Condition('AND');
  $condition
    ->condition(SynonymsFindProviderInterface::COLUMN_SYNONYM_PLACEHOLDER, $name);
  $found_entity_ids = [];
  $synonyms_found = $this->findSynonymsService
    ->findSynonyms($condition, $entity_type, $bundle, '*');
  if (isset($synonyms_found[0]->entity_id)) {
    $found_entity_ids[] = $synonyms_found[0]->entity_id;
  }
  return $found_entity_ids;
}