You are here

public function CommerceShippingCurrency::shippingCurrency in Commerce Currency Resolver 8

Calculate rates based on current currency.

Parameters

\Drupal\commerce_shipping\Event\ShippingRatesEvent $event: The order event.

File

modules/shipping/src/EventSubscriber/CommerceShippingCurrency.php, line 59

Class

CommerceShippingCurrency
Handling shipments rates.

Namespace

Drupal\commerce_currency_resolver_shipping\EventSubscriber

Code

public function shippingCurrency(ShippingRatesEvent $event) {

  /** @var \Drupal\commerce_shipping\ShippingRate[] $rates */
  if ($rates = $event
    ->getRates()) {
    if ($this
      ->isShippingAdminRoute()) {
      $resolved_currency = $event
        ->getShipment()
        ->getAmount()
        ->getCurrencyCode();
    }
    else {
      $resolved_currency = $this->currentCurrency
        ->getCurrency();
    }
    $shipping_conversion = [];
    foreach ($rates as $key => $rate) {
      if ($rate
        ->getAmount()
        ->getCurrencyCode() != $resolved_currency) {
        $plugin_data = $event
          ->getShippingMethod()
          ->getPlugin()
          ->getConfiguration();

        // Check if they are entered separate prices per currencies.
        if (isset($plugin_data['fields'][$resolved_currency]) && is_numeric($plugin_data['fields'][$resolved_currency]['number'])) {
          $resolved_price = new Price((string) $plugin_data['fields'][$resolved_currency]['number'], $plugin_data['fields'][$resolved_currency]['currency_code']);
          $rate
            ->setOriginalAmount($resolved_price);
          $rate
            ->setAmount($resolved_price);
        }
        else {
          $rate
            ->setAmount($this->priceExchanger
            ->priceConversion($rate
            ->getAmount(), $resolved_currency));
          $rate
            ->setOriginalAmount($this->priceExchanger
            ->priceConversion($rate
            ->getOriginalAmount(), $resolved_currency));
        }
        $shipping_conversion[$key] = $rate;
      }
    }
    if ($shipping_conversion) {
      $event
        ->setRates($shipping_conversion);
    }
  }
}