You are here

public static function Importer::createSynonym in Search API Synonym 8

Create / update a synonym.

Parameters

string $word: The source word we add the synonym for.

array $synonyms: Simple array with synonyms.

string $type: The synonym type.

array $settings: Import settings.

array $context: Batch context - also used for storing results in non batch operations.

File

src/Import/Importer.php, line 173

Class

Importer
Importer class.

Namespace

Drupal\search_api_synonym\Import

Code

public static function createSynonym($word, array $synonyms, $type, array $settings, array &$context) {
  $request_time = \Drupal::time()
    ->getRequestTime();

  // Check if we have an existing synonym entity we should update.
  $sid = Importer::lookUpSynonym($word, $type, $settings['langcode']);

  // Trim spaces from synonyms.
  $synonyms = array_map('trim', $synonyms);

  // Load and update existing synonym entity.
  if ($sid) {
    $entity = Synonym::load($sid);

    // Update method = Merge.
    if ($settings['update_existing'] == 'merge') {
      $existing = $entity
        ->getSynonyms();
      $existing = array_map('trim', explode(',', $existing));
      $synonyms = array_unique(array_merge($existing, $synonyms));
    }
    $synonyms_str = implode(',', $synonyms);
    $entity
      ->setSynonyms($synonyms_str);
  }
  else {
    $entity = Synonym::create([
      'langcode' => $settings['langcode'],
    ]);
    $uid = \Drupal::currentUser()
      ->id();
    $entity
      ->setOwnerId($uid);
    $entity
      ->setCreatedTime($request_time);
    $entity
      ->setType($type);
    $entity
      ->setWord($word);
    $synonyms_str = implode(',', $synonyms);
    $entity
      ->setSynonyms($synonyms_str);
  }
  $entity
    ->setChangedTime($request_time);
  $entity
    ->setActive($settings['status']);
  $entity
    ->save();
  if ($sid = $entity
    ->id()) {
    $context['results']['success'][] = $sid;
  }
  else {
    $context['results']['errors'][] = [
      'word' => $word,
      'synonyms' => $synonyms,
    ];
  }
}