You are here

public function CurrencyImporter::import in Price 8

Same name and namespace in other branches
  1. 3.x src/CurrencyImporter.php \Drupal\price\CurrencyImporter::import()
  2. 2.0.x src/CurrencyImporter.php \Drupal\price\CurrencyImporter::import()
  3. 2.x src/CurrencyImporter.php \Drupal\price\CurrencyImporter::import()
  4. 3.0.x src/CurrencyImporter.php \Drupal\price\CurrencyImporter::import()

Imports currency data for the given currency code.

Parameters

string $currency_code: The currency code.

Return value

\Drupal\price\Entity\CurrencyInterface The saved currency entity.

Throws

\CommerceGuys\Intl\Exception\UnknownCurrencyException Thrown when the currency couldn't be found in the library definitions.

Overrides CurrencyImporterInterface::import

1 call to CurrencyImporter::import()
CurrencyImporter::importByCountry in src/CurrencyImporter.php
Imports currency data for the given country code.

File

src/CurrencyImporter.php, line 73

Class

CurrencyImporter
Default implementation of the currency importer.

Namespace

Drupal\price

Code

public function import($currency_code) {
  if ($existing_entity = $this->storage
    ->load($currency_code)) {

    // Pretend the currency was just imported.
    return $existing_entity;
  }
  $default_langcode = $this->languageManager
    ->getDefaultLanguage()
    ->getId();
  $currency = $this->externalRepository
    ->get($currency_code, $default_langcode, 'en');
  $values = [
    'langcode' => $default_langcode,
    'currencyCode' => $currency
      ->getCurrencyCode(),
    'name' => $currency
      ->getName(),
    'numericCode' => $currency
      ->getNumericCode(),
    'symbol' => $currency
      ->getSymbol(),
    'fractionDigits' => $currency
      ->getFractionDigits(),
  ];

  /** @var \Drupal\price\Entity\CurrencyInterface $entity */
  $entity = $this->storage
    ->create($values);
  $entity
    ->trustData()
    ->save();
  if ($this->languageManager
    ->isMultilingual()) {

    // Import translations for any additional languages the site has.
    $languages = $this->languageManager
      ->getLanguages(LanguageInterface::STATE_CONFIGURABLE);
    $languages = array_diff_key($languages, [
      $default_langcode => $default_langcode,
    ]);
    $langcodes = array_map(function ($language) {
      return $language
        ->getId();
    }, $languages);
    $this
      ->importEntityTranslations($entity, $langcodes);
  }
  return $entity;
}