You are here

public function EarlyOrderProcessor::process in Commerce Shipping 8.2

Processes an order.

Parameters

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

Overrides OrderProcessorInterface::process

File

src/EarlyOrderProcessor.php, line 62

Class

EarlyOrderProcessor
Prepares shipments for the order refresh process.

Namespace

Drupal\commerce_shipping

Code

public function process(OrderInterface $order) {
  if (!$this->shippingOrderManager
    ->hasShipments($order)) {
    return;
  }

  /** @var \Drupal\commerce_shipping\Entity\ShipmentInterface[] $shipments */
  $shipments = $order
    ->get('shipments')
    ->referencedEntities();
  if ($shipments && $this
    ->shouldRepack($order, $shipments)) {
    $shipping_profile = $this->shippingOrderManager
      ->getProfile($order);

    // If the shipping profile does not exist, delete all shipments.
    if (!$shipping_profile) {
      $shipment_storage = $this->entityTypeManager
        ->getStorage('commerce_shipment');
      $shipment_storage
        ->delete($shipments);
      return;
    }
    $shipments = $this->shippingOrderManager
      ->pack($order, $shipping_profile);
  }
  $should_refresh = $this
    ->shouldRefresh($order);
  foreach ($shipments as $key => $shipment) {
    if ($original_amount = $shipment
      ->getOriginalAmount()) {
      $shipment
        ->setAmount($original_amount);
    }
    $shipment
      ->clearAdjustments();
    if (!$should_refresh) {
      continue;
    }
    $shipment->order_id->entity = $order;
    $rates = $this->shipmentManager
      ->calculateRates($shipment);

    // There is no rates for shipping. "clear" the rate...
    // Note that we don't remove the shipment to prevent data loss (we're
    // mainly interested in preserving the shipping profile).
    if (empty($rates)) {
      $shipment
        ->clearRate();
      continue;
    }
    $rate = $this->shipmentManager
      ->selectDefaultRate($shipment, $rates);
    $this->shipmentManager
      ->applyRate($shipment, $rate);
  }

  // Unset flag before returning updated shipments.
  if ($should_refresh) {
    $order
      ->unsetData(ShippingOrderManagerInterface::FORCE_REFRESH);
  }
  $order
    ->set('shipments', $shipments);
}