You are here

protected function Shipment::recalculateWeight in Commerce Shipping 8.2

Recalculates the shipment's weight.

5 calls to Shipment::recalculateWeight()
Shipment::addItem in src/Entity/Shipment.php
Adds a shipment item.
Shipment::prepareFields in src/Entity/Shipment.php
Ensures that the package_type and weight fields are populated.
Shipment::removeItem in src/Entity/Shipment.php
Removes a shipment item.
Shipment::setItems in src/Entity/Shipment.php
Sets the shipment items.
Shipment::setPackageType in src/Entity/Shipment.php
Sets the package type.

File

src/Entity/Shipment.php, line 525

Class

Shipment
Defines the shipment entity class.

Namespace

Drupal\commerce_shipping\Entity

Code

protected function recalculateWeight() {
  if (!$this
    ->hasItems()) {

    // Can't calculate the weight if the items are still unavailable.
    return;
  }

  /** @var \Drupal\physical\Weight $weight */
  $weight = NULL;
  foreach ($this
    ->getItems() as $shipment_item) {
    $shipment_item_weight = $shipment_item
      ->getWeight();
    $weight = $weight ? $weight
      ->add($shipment_item_weight) : $shipment_item_weight;
  }
  if ($package_type = $this
    ->getPackageType()) {
    $package_type_weight = $package_type
      ->getWeight();
    $weight = $weight
      ->add($package_type_weight);
  }
  $this
    ->setWeight($weight);
}