You are here

protected static function FedEx::getPackageTotalVolume in Commerce FedEx 8

Return the total volume of an array of shipment items in a given unit.

Parameters

array $shipment_items: The array of shipment items.

string $volume_unit: The volume unit.

Return value

\Drupal\physical\Volume The total Volume.

Throws

\Exception

1 call to FedEx::getPackageTotalVolume()
FedEx::calculatePackageCount in src/Plugin/Commerce/ShippingMethod/FedEx.php
Determines a package count given package and item volumes.

File

src/Plugin/Commerce/ShippingMethod/FedEx.php, line 915

Class

FedEx
Provides the FedEx shipping method.

Namespace

Drupal\commerce_fedex\Plugin\Commerce\ShippingMethod

Code

protected static function getPackageTotalVolume(array $shipment_items, $volume_unit = NULL) {
  if ($volume_unit == NULL) {
    $volume_unit = VolumeUnit::CUBIC_CENTIMETER;
  }
  switch ($volume_unit) {
    case VolumeUnit::CUBIC_CENTIMETER:
      $linear_unit = PhysicalLengthUnits::CENTIMETER;
      break;
    case VolumeUnit::CUBIC_INCH:
      $linear_unit = PhysicalLengthUnits::INCH;
      break;
    default:
      throw new \Exception("Invalid Units");
  }
  $order_item_storage = \Drupal::entityTypeManager()
    ->getStorage('commerce_order_item');
  $order_item_ids = [];
  foreach ($shipment_items as $shipment_item) {
    $order_item_ids[] = $shipment_item
      ->getOrderItemId();
  }
  $order_items = $order_item_storage
    ->loadMultiple($order_item_ids);
  $total_volume = 0;
  foreach ($order_items as $order_item) {

    /** @var \Drupal\commerce_order\Entity\OrderItem $order_item */

    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $purchased_entity */
    $purchased_entity = $order_item
      ->getPurchasedEntity();
    if ($purchased_entity
      ->hasField('dimensions') && !$purchased_entity
      ->get('dimensions')
      ->isEmpty()) {

      /** @var \Drupal\physical\Plugin\Field\FieldType\DimensionsItem $dimensions */
      $dimensions = $purchased_entity
        ->get('dimensions')
        ->first();
      $volume = $dimensions
        ->getHeight()
        ->convert($linear_unit)
        ->multiply($dimensions
        ->getWidth()
        ->convert($linear_unit)
        ->getNumber())
        ->multiply($dimensions
        ->getLength()
        ->convert($linear_unit)
        ->getNumber())
        ->getNumber();
      $total_volume += (double) $volume * $order_item
        ->getQuantity();
    }
  }
  return new Volume((string) $total_volume, $volume_unit);
}