You are here

function commerce_physical_order_volume in Commerce Physical Product 7

Determines the volume of an entire order.

Parameters

commerce_order $order: The order object whose volume should be calculated.

string $unit: The unit of measurement to convert dimensions to before calculating the volume of the order in the related cubic unit.

Return value

array A volume value array with keys representing the total 'volume' of the order in the 'unit' specified or NULL if no volume could be determined.

File

./commerce_physical.module, line 224
API for working with physical product types in Drupal Commerce.

Code

function commerce_physical_order_volume($order, $unit = 'in') {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $volume = NULL;

  // Loop over each line item on the order.
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {

    // Get the dimensions value of product line items.
    if (in_array($line_item_wrapper->type
      ->value(), commerce_product_line_item_types())) {
      $line_item_dimensions = commerce_physical_product_line_item_dimensions($line_item_wrapper
        ->value());

      // Each product in a line item has the same dimensions, so we index into
      // only the first product.
      $line_item_dimensions = reset($line_item_dimensions);

      // Add it to the running total converting it to the required weight unit.
      if (!physical_field_is_empty($line_item_dimensions, array(
        'type' => 'physical_dimensions',
      ))) {
        $converted_dimensions = physical_dimensions_convert($line_item_dimensions, $unit);
        $converted_dimensions['volume'] = $converted_dimensions['width'] * $converted_dimensions['length'] * $converted_dimensions['height'] * $line_item_wrapper->quantity
          ->value();
        if (empty($volume['volume'])) {

          // Create a volume value array using the converted unit type.
          $volume = array(
            'volume' => $converted_dimensions['volume'],
            'unit' => $unit,
          );
        }
        else {
          $volume['volume'] += $converted_dimensions['volume'];
        }
      }
    }
  }

  // Allow other modules to alter the volume if necessary.
  drupal_alter('commerce_physical_order_volume', $volume, $order, $unit);
  return $volume;
}