You are here

public function CurrencyImporter::import in Commerce Core 8.2

Imports currency data for the given currency code.

Parameters

string $currency_code: The currency code.

Return value

\Drupal\commerce_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 modules/price/src/CurrencyImporter.php
Imports currency data for the given country code.

File

modules/price/src/CurrencyImporter.php, line 74

Class

CurrencyImporter
Default implementation of the currency importer.

Namespace

Drupal\commerce_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\commerce_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;
}