You are here

public function OrderEventSubscriber::onOrderDelete in Commerce Stock 8

Performs a stock transaction on an order delete event.

This happens on PREDELETE since the items are not available after DELETE.

Parameters

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

File

src/EventSubscriber/OrderEventSubscriber.php, line 203

Class

OrderEventSubscriber
Performs stock transactions on order and order item events.

Namespace

Drupal\commerce_stock\EventSubscriber

Code

public function onOrderDelete(OrderEvent $event) {
  $eventType = $this
    ->getEventType('commerce_stock_order_delete');
  $order = $event
    ->getOrder();
  if ($order
    ->getState()
    ->getWorkflow()
    ->getGroup() !== 'commerce_order') {
    return;
  }
  if (in_array($order
    ->getState()->value, [
    'draft',
    'canceled',
  ])) {
    return;
  }
  $items = $order
    ->getItems();
  foreach ($items as $item) {
    $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;
    }
    $quantity = $item
      ->getQuantity();
    $context = self::createContextFromOrder($order);
    $location = $this->stockServiceManager
      ->getTransactionLocation($context, $entity, $quantity);
    $transaction_type = StockTransactionsInterface::STOCK_RETURN;
    $this
      ->runTransactionEvent($eventType, $context, $entity, $quantity, $location, $transaction_type, $order);
  }
}