public function USPSRateRequest::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/
USPSRateRequest.php, line 34
Class
- USPSRateRequest
- Class USPSRateRequest.
Namespace
Drupal\commerce_uspsCode
public function resolveRates(array $response) {
$rates = [];
// Parse the rate response and create shipping rates array.
if (!empty($response['RateV4Response']['Package']['Postage'])) {
// Convert the postage response to an array of rates when
// only 1 rate is returned.
if (!empty($response['RateV4Response']['Package']['Postage']['Rate'])) {
$response['RateV4Response']['Package']['Postage'] = [
$response['RateV4Response']['Package']['Postage'],
];
}
foreach ($response['RateV4Response']['Package']['Postage'] as $rate) {
$price = $rate['Rate'];
// 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($rate['CommercialPlusRate']) ? $rate['CommercialPlusRate'] : $price;
break;
case 'commercial':
$price = !empty($rate['CommercialRate']) ? $rate['CommercialRate'] : $price;
break;
}
}
$service_code = $rate['@attributes']['CLASSID'];
$service_name = $this
->cleanServiceName($rate['MailService']);
// Class code 0 is used for multiple services in the
// response. The only way to determine which service
// is returned is to parse the service name for matching
// strings based on the service type. All other service
// codes are unique and do not require this extra step.
if ($service_code == 0) {
if (stripos($service_name, 'Envelope') !== FALSE) {
$service_code = self::FIRST_CLASS_MAIL_ENVELOPE;
}
elseif (stripos($service_name, 'Letter') !== FALSE) {
$service_code = self::FIRST_CLASS_MAIL_LETTER;
}
elseif (stripos($service_name, 'Postcards') !== FALSE) {
$service_code = self::FIRST_CLASS_MAIL_POSTCARDS;
}
elseif (stripos($service_name, 'Package') !== FALSE) {
$service_code = self::FIRST_CLASS_MAIL_PACKAGE;
}
else {
continue;
}
}
// 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;
}