You are here

public function CommerceSmartImporerService::createTaxonomyTerm in Commerce Smart Importer 8

Creates Taxonomy term value based on field settings.

1 call to CommerceSmartImporerService::createTaxonomyTerm()
CommerceSmartImporerService::formatField in src/Plugin/CommerceSmartImporerService.php
Formats one field value based on field settings.

File

src/Plugin/CommerceSmartImporerService.php, line 526
Main Commerce Smart Importer Service.

Class

CommerceSmartImporerService
This is main Commerce Smart Importer Service.

Namespace

Drupal\commerce_smart_importer\Plugin

Code

public function createTaxonomyTerm($name, $reference, $create = TRUE) {
  $vocabularies = Vocabulary::loadMultiple();
  if (isset($vocabularies[$reference])) {
    $vocab = $vocabularies[$reference];
  }
  else {
    foreach ($vocabularies as $key => $vocabulary) {
      if ($vocabulary
        ->get('name') == $reference) {
        $reference = $key;
        $vocab = $vocabulary;
        break;
      }
    }
  }
  if (!isset($vocab)) {
    throw new Exception('Vocabulary does not exist');
  }
  $query = $this
    ->entityTypeManager()
    ->getStorage('taxonomy_term')
    ->getQuery();
  $query
    ->condition('vid', $reference);
  $query
    ->condition('name', $name);
  $taxonomyId = $query
    ->execute();
  if (empty($taxonomyId) && $create) {
    $term = Term::create([
      'vid' => $reference,
      'name' => $name,
    ]);
    $term
      ->save();
    $taxonomyId = $term
      ->id();
  }
  if (!$create) {
    return [
      'target_id' => uniqid(),
    ];
  }
  return is_array($taxonomyId) ? [
    'target_id' => current($taxonomyId),
  ] : [
    'target_id' => $taxonomyId,
  ];
}