You are here

protected function OrderStorage::doOrderPreSave in Commerce Core 8.2

Performs order-specific pre-save tasks.

This includes:

  • Refreshing the order.
  • Recalculating the total price.
  • Dispatching the "order paid" event.

Parameters

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

1 call to OrderStorage::doOrderPreSave()
OrderStorage::invokeHook in modules/order/src/OrderStorage.php
Invokes a hook on behalf of the entity.

File

modules/order/src/OrderStorage.php, line 125

Class

OrderStorage
Defines the order storage.

Namespace

Drupal\commerce_order

Code

protected function doOrderPreSave(OrderInterface $order) {

  // Ensure the order doesn't reference any removed order item by resetting
  // the "order_items" field with order items that were successfully loaded
  // from the database.
  $order
    ->set('order_items', $order
    ->getItems());
  if ($order
    ->getRefreshState() == OrderInterface::REFRESH_ON_SAVE) {
    $this->orderRefresh
      ->refresh($order);
  }

  // Only the REFRESH_ON_LOAD state needs to be persisted on the entity.
  if ($order
    ->getRefreshState() != OrderInterface::REFRESH_ON_LOAD) {
    $order
      ->setRefreshState(NULL);
  }
  $order
    ->recalculateTotalPrice();

  // Notify other modules if the order has been fully paid.
  $original_paid = isset($order->original) ? $order->original
    ->isPaid() : FALSE;
  if ($order
    ->isPaid() && !$original_paid) {

    // Order::preSave() initializes the 'paid_event_dispatched' flag to FALSE.
    // Skip dispatch if it already happened once (flag is TRUE), or if the
    // order was completed before Commerce 8.x-2.10 (flag is NULL).
    if ($order
      ->getData('paid_event_dispatched') === FALSE) {
      $event = new OrderEvent($order);
      $this->eventDispatcher
        ->dispatch(OrderEvents::ORDER_PAID, $event);
      $order
        ->setData('paid_event_dispatched', TRUE);
    }
  }
}