You are here

function commerce_price_components_combine in Commerce Core 7

Combines the price components of two prices into one components array, merging all components of the same type into a single component.

Parameters

$price: The base price array whose full data array will be returned.

$price2: A price array whose components will be combined with those of the base price.

Return value

A data array with the two sets of components combined but without any additional data from $price2's data array.

1 call to commerce_price_components_combine()
commerce_order_calculate_total in modules/order/commerce_order.module
Calculates the order total, updating the commerce_order_total field data in the order object this function receives.

File

modules/price/commerce_price.module, line 1033
Defines the Price field with widgets and formatters used to add prices with currency codes to various Commerce entities.

Code

function commerce_price_components_combine($price, $price2) {

  // Ensure the base price data array has a components array.
  if (empty($price['data']['components'])) {
    $price['data']['components'] = array();
  }

  // Loop over the components in the second price's data array.
  foreach ($price2['data']['components'] as $key => $component) {

    // Convert the component to the proper currency first.
    if ($component['price']['currency_code'] != $price['currency_code']) {
      $component['price']['amount'] = commerce_currency_convert($component['price']['amount'], $component['price']['currency_code'], $price['currency_code']);
      $component['price']['currency_code'] = $price['currency_code'];
    }

    // Look for a matching component in the base price data array.
    $matched = FALSE;
    foreach ($price['data']['components'] as $base_key => $base_component) {

      // If the component type matches the component in question...
      if ($base_component['name'] == $component['name']) {

        // Add the two prices together and mark this as a match.
        $price['data']['components'][$base_key]['price']['amount'] += $component['price']['amount'];
        $matched = TRUE;
      }
    }

    // If no match was found, bring the component in as is.
    if (!$matched) {
      $price['data']['components'][] = $component;
    }
  }
  return $price['data'];
}