You are here

public function OrderRefresh::refresh in Commerce Core 8.2

Refreshes the given order.

Any modified order items will be automatically saved. The order itself will not be saved.

Parameters

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

Overrides OrderRefreshInterface::refresh

File

modules/order/src/OrderRefresh.php, line 148

Class

OrderRefresh
Default implementation for order refresh.

Namespace

Drupal\commerce_order

Code

public function refresh(OrderInterface $order) {

  // First invoke order preprocessors if any.
  foreach ($this->preprocessors as $processor) {
    $processor
      ->preprocess($order);
  }
  $current_time = $this->time
    ->getCurrentTime();
  $order
    ->setChangedTime($current_time);
  $order
    ->clearAdjustments();

  // Nothing else can be done while the order is empty.
  if (!$order
    ->hasItems()) {
    return;
  }
  $time = $order
    ->getCalculationDate()
    ->format('U');
  $context = new Context($order
    ->getCustomer(), $order
    ->getStore(), $time);
  foreach ($order
    ->getItems() as $order_item) {
    $purchased_entity = $order_item
      ->getPurchasedEntity();
    if ($purchased_entity) {
      $order_item
        ->setTitle($purchased_entity
        ->getOrderItemTitle());
      if (!$order_item
        ->isUnitPriceOverridden()) {
        $unit_price = $this->chainPriceResolver
          ->resolve($purchased_entity, $order_item
          ->getQuantity(), $context);
        $order_item
          ->setUnitPrice($unit_price);
      }
    }

    // If the order refresh is running during order preSave(),
    // $order_item->getOrder() will point to the original order (or
    // NULL, in case the order item is new).
    $order_item->order_id->entity = $order;
  }

  // Allow the processors to modify the order and its items.
  foreach ($this->processors as $processor) {
    $processor
      ->process($order);
    if (!$order
      ->hasItems()) {
      return;
    }
  }
  foreach ($order
    ->getItems() as $order_item) {
    if ($order_item
      ->hasTranslationChanges()) {

      // Remove order items which had their quantities set to 0.
      if (Calculator::compare($order_item
        ->getQuantity(), '0') === 0) {
        $order
          ->removeItem($order_item);
        $order_item
          ->delete();
      }
      else {

        // Remove the order that was set above, to avoid
        // crashes during the entity save process.
        $order_item->order_id->entity = NULL;
        $order_item
          ->setChangedTime($current_time);
        $order_item
          ->save();
      }
    }
  }
}