You are here

public function CoreStockEvents::stockEvent in Commerce Stock 8

A stock event with transaction details.

The stock event gets both the details about the type of the event and the transaction it should create. It can simply create the transaction from the details provided, add logic to check if the transaction is to be created or override the details provided before creating the transaction.

Parameters

\Drupal\commerce\Context $context: The context containing the customer & store.

\Drupal\commerce\PurchasableEntityInterface $entity: The purchasable entity.

int $stockEvent: The event ID that's responsible for the transaction.

int $quantity: The quantity.

\Drupal\commerce_stock\StockLocationInterface $location: The stock location.

int $transaction_type: The transaction type ID.

array $metadata: Holds all the optional values those are:

  • related_oid: related order.
  • related_uid: related user.
  • data: Serialized data array holding a message.

Return value

int Return the ID of the transaction or FALSE if no transaction created.

Overrides StockEventsInterface::stockEvent

File

src/Plugin/StockEvents/CoreStockEvents.php, line 24

Class

CoreStockEvents
Core Stock Events.

Namespace

Drupal\commerce_stock\Plugin\StockEvents

Code

public function stockEvent(Context $context, PurchasableEntityInterface $entity, $stockEvent, $quantity, StockLocationInterface $location, $transaction_type, array $metadata) {
  $config = \Drupal::configFactory()
    ->get('commerce_stock.core_stock_events');

  // Check if event should be handled.
  $order_placed_events = [
    StockEventsInterface::ORDER_PLACE_EVENT,
  ];
  $order_update_events = [
    StockEventsInterface::ORDER_UPDATE_EVENT,
    StockEventsInterface::ORDER_ITEM_UPDATE_EVENT,
  ];
  $order_delete_events = [
    StockEventsInterface::ORDER_CANCEL_EVENT,
    StockEventsInterface::ORDER_DELET_EVENT,
    StockEventsInterface::ORDER_ITEM_DELETE_EVENT,
  ];

  // Cancel if event type is not enabled.
  if (in_array($stockEvent, $order_placed_events) && !$config
    ->get('core_stock_events_order_complete')) {
    return FALSE;
  }
  elseif (in_array($stockEvent, $order_update_events) && !$config
    ->get('core_stock_events_order_updates')) {
    return FALSE;
  }
  elseif (in_array($stockEvent, $order_delete_events) && !$config
    ->get('core_stock_events_order_cancel')) {
    return FALSE;
  }

  // Get the stock service.
  $stockService = \Drupal::service('commerce_stock.service_manager')
    ->getService($entity);

  // Use the stock updater to create the transaction.
  $transaction_id = $stockService
    ->getStockUpdater()
    ->createTransaction($entity, $location
    ->getId(), '', $quantity, NULL, $currency_code = NULL, $transaction_type, $metadata);

  // Return the transaction ID.
  return $transaction_id;
}