You are here

public function USPSRateRequestInternational::resolveRates in Commerce USPS 8

Resolve the rates from the RateRequest response.

Parameters

array $response: The rate request array.

Return value

array An array of ShippingRates or an empty array.

Overrides USPSRateRequestInterface::resolveRates

File

src/USPSRateRequestInternational.php, line 25

Class

USPSRateRequestInternational
Class USPSRateRequest.

Namespace

Drupal\commerce_usps

Code

public function resolveRates(array $response) {
  $rates = [];

  // Parse the rate response and create shipping rates array.
  if (!empty($response['IntlRateV2Response']['Package']['Service'])) {

    // Convert the service response to an array of rates when
    // only 1 rate is returned.
    if (!empty($response['IntlRateV2Response']['Package']['Service']['Postage'])) {
      $response['IntlRateV2Response']['Package']['Service'] = [
        $response['IntlRateV2Response']['Package']['Service'],
      ];
    }
    foreach ($response['IntlRateV2Response']['Package']['Service'] as $service) {
      $price = $service['Postage'];

      // Attempt to use an alternate rate class if selected.
      if (!empty($this->configuration['rate_options']['rate_class'])) {
        switch ($this->configuration['rate_options']['rate_class']) {
          case 'commercial_plus':
            $price = !empty($service['CommercialPlusPostage']) ? $service['CommercialPlusPostage'] : $price;
            break;
          case 'commercial':
            $price = !empty($service['CommercialPostage']) ? $service['CommercialPostage'] : $price;
            break;
        }
      }
      $service_code = $service['@attributes']['ID'];
      $service_name = $this
        ->cleanServiceName($service['SvcDescription']);

      // Only add the rate if this service is enabled.
      if (!in_array($service_code, $this->configuration['services'])) {
        continue;
      }
      $rates[] = new ShippingRate([
        'shipping_method_id' => $this->shippingMethod
          ->id(),
        'service' => new ShippingService($service_code, $service_name),
        'amount' => new Price($price, 'USD'),
      ]);
    }
  }
  return $rates;
}