You are here

public function TestPacker::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

tests/modules/commerce_shipping_test/src/Packer/TestPacker.php, line 31

Class

TestPacker
Creates a shipment per order item.

Namespace

Drupal\commerce_shipping_test\Packer

Code

public function pack(OrderInterface $order, ProfileInterface $shipping_profile) {
  $proposed_shipments = [];
  foreach ($order
    ->getItems() as $index => $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();
    $proposed_shipments[] = new ProposedShipment([
      'type' => 'default',
      'order_id' => $order
        ->id(),
      'title' => t('Shipment #@index', [
        '@index' => $index + 1,
      ]),
      '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),
        ]),
      ],
      'shipping_profile' => $shipping_profile,
    ]);
  }
  return $proposed_shipments;
}