You are here

public function DefaultPacker::pack in Commerce Shipping 8.2

Packs the given order.

Parameters

\Drupal\commerce_order\Entity\OrderInterface $order: The order.

\Drupal\profile\Entity\ProfileInterface $shipping_profile: The shipping profile.

Return value

\Drupal\commerce_shipping\ProposedShipment[] The proposed shipments.

Overrides PackerInterface::pack

File

src/Packer/DefaultPacker.php, line 53

Class

DefaultPacker
Creates a single shipment per order.

Namespace

Drupal\commerce_shipping\Packer

Code

public function pack(OrderInterface $order, ProfileInterface $shipping_profile) {
  $items = [];
  foreach ($order
    ->getItems() as $order_item) {
    $purchased_entity = $order_item
      ->getPurchasedEntity();

    // Ship only shippable purchasable entity types.
    if (!$purchased_entity || !$purchased_entity
      ->hasField('weight')) {
      continue;
    }

    // The weight will be empty if the shippable trait was added but the
    // existing entities were not updated.
    if ($purchased_entity
      ->get('weight')
      ->isEmpty()) {
      $purchased_entity
        ->set('weight', new Weight(0, WeightUnit::GRAM));
    }
    $quantity = $order_item
      ->getQuantity();
    if (Calculator::compare($order_item
      ->getQuantity(), '0') == 0) {
      continue;
    }

    /** @var \Drupal\physical\Weight $weight */
    $weight = $purchased_entity
      ->get('weight')
      ->first()
      ->toMeasurement();
    $items[] = new ShipmentItem([
      'order_item_id' => $order_item
        ->id(),
      'title' => $order_item
        ->getTitle(),
      'quantity' => $quantity,
      'weight' => $weight
        ->multiply($quantity),
      'declared_value' => $order_item
        ->getUnitPrice()
        ->multiply($quantity),
    ]);
  }
  $proposed_shipments = [];
  if (!empty($items)) {
    $proposed_shipments[] = new ProposedShipment([
      'type' => $this
        ->getShipmentType($order),
      'order_id' => $order
        ->id(),
      'title' => $this
        ->t('Shipment #1'),
      'items' => $items,
      'shipping_profile' => $shipping_profile,
    ]);
  }
  return $proposed_shipments;
}