You are here

public function OrderEventSubscriber::onOrderItemUpdate in Commerce Stock 8

Performs a stock transaction on an order item update.

Parameters

\Drupal\commerce_order\Event\OrderItemEvent $event: The order item event.

File

src/EventSubscriber/OrderEventSubscriber.php, line 240

Class

OrderEventSubscriber
Performs stock transactions on order and order item events.

Namespace

Drupal\commerce_stock\EventSubscriber

Code

public function onOrderItemUpdate(OrderItemEvent $event) {
  $eventType = $this
    ->getEventType('commerce_stock_order_item_update');
  $item = $event
    ->getOrderItem();
  $order = $item
    ->getOrder();
  if ($order && !in_array($order
    ->getState()->value, [
    'draft',
    'canceled',
  ])) {
    if ($order
      ->getState()
      ->getWorkflow()
      ->getGroup() !== 'commerce_order') {
      return;
    }
    $original = $this
      ->getOriginalEntity($item);
    $diff = $original
      ->getQuantity() - $item
      ->getQuantity();
    if ($diff) {
      $entity = $item
        ->getPurchasedEntity();
      if (!$entity) {
        return;
      }
      $service = $this->stockServiceManager
        ->getService($entity);
      $checker = $service
        ->getStockChecker();

      // If always in stock then no need to create a transaction.
      if ($checker
        ->getIsAlwaysInStock($entity)) {
        return;
      }
      $transaction_type = $diff < 0 ? StockTransactionsInterface::STOCK_SALE : StockTransactionsInterface::STOCK_RETURN;
      $context = self::createContextFromOrder($order);
      $location = $this->stockServiceManager
        ->getTransactionLocation($context, $entity, $diff);
      $this
        ->runTransactionEvent($eventType, $context, $entity, $diff, $location, $transaction_type, $order);
    }
  }
}