You are here

public function OrderEventSubscriber::onOrderUpdate in Commerce Stock 8

Acts on the order update event to create transactions for new items.

The reason this isn't handled by OrderEvents::ORDER_ITEM_INSERT is because that event never has the correct values.

Parameters

\Drupal\commerce_order\Event\OrderEvent $event: The order event.

File

src/EventSubscriber/OrderEventSubscriber.php, line 124

Class

OrderEventSubscriber
Performs stock transactions on order and order item events.

Namespace

Drupal\commerce_stock\EventSubscriber

Code

public function onOrderUpdate(OrderEvent $event) {
  $eventType = $this
    ->getEventType('commerce_stock_order_update');
  $order = $event
    ->getOrder();
  if ($order
    ->getState()
    ->getWorkflow()
    ->getGroup() !== 'commerce_order') {
    return;
  }
  $original_order = $this
    ->getOriginalEntity($order);
  foreach ($order
    ->getItems() as $item) {
    if (!$original_order
      ->hasItem($item)) {
      if ($order && !in_array($order
        ->getState()->value, [
        'draft',
        'canceled',
      ])) {
        $entity = $item
          ->getPurchasedEntity();
        if (!$entity) {
          continue;
        }
        $service = $this->stockServiceManager
          ->getService($entity);
        $checker = $service
          ->getStockChecker();

        // If always in stock then no need to create a transaction.
        if ($checker
          ->getIsAlwaysInStock($entity)) {
          continue;
        }
        $context = self::createContextFromOrder($order);
        $location = $this->stockServiceManager
          ->getTransactionLocation($context, $entity, $item
          ->getQuantity());
        $transaction_type = StockTransactionsInterface::STOCK_SALE;
        $quantity = -1 * $item
          ->getQuantity();
        $this
          ->runTransactionEvent($eventType, $context, $entity, $quantity, $location, $transaction_type, $order);
      }
    }
  }
}