You are here

protected function EarlyOrderProcessor::shouldRepack in Commerce Shipping 8.2

Determines whether the given order's shipments should be repacked.

Parameters

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

\Drupal\commerce_shipping\Entity\ShipmentInterface[] $shipments: The shipments.

Return value

bool TRUE if the order should be repacked, FALSE otherwise.

1 call to EarlyOrderProcessor::shouldRepack()
EarlyOrderProcessor::process in src/EarlyOrderProcessor.php
Processes an order.

File

src/EarlyOrderProcessor.php, line 122

Class

EarlyOrderProcessor
Prepares shipments for the order refresh process.

Namespace

Drupal\commerce_shipping

Code

protected function shouldRepack(OrderInterface $order, array $shipments) {

  // Skip repacking if there's at least one shipment that was created outside
  // of the packing process (via the admin UI, for example).
  foreach ($shipments as $shipment) {
    if (!$shipment
      ->getData('owned_by_packer')) {
      return FALSE;
    }
  }

  // Flag used for force repacking shipments and possible recalculation
  // of rates.
  if ($this
    ->shouldRefresh($order)) {
    return TRUE;
  }

  // Ideally repacking would happen only if the order items changed.
  // However, it is not possible to detect order item quantity changes,
  // because the order items are saved before the order itself.
  // Therefore, repacking runs on every refresh, but as a minimal
  // optimization, this processor ignores refreshes caused by moving
  // through checkout, unless an order item was added/removed along the way.
  if (isset($order->original) && $order
    ->hasField('checkout_step')) {
    $previous_step = $order->original
      ->get('checkout_step')->value;
    $current_step = $order
      ->get('checkout_step')->value;
    $previous_order_item_ids = array_map(function ($value) {
      return $value['target_id'];
    }, $order->original
      ->get('order_items')
      ->getValue());
    $current_order_item_ids = array_map(function ($value) {
      return $value['target_id'];
    }, $order
      ->get('order_items')
      ->getValue());
    if ($previous_step != $current_step && $previous_order_item_ids == $current_order_item_ids) {
      return FALSE;
    }
  }
  return TRUE;
}