You are here

public function StockServiceManager::moveStock in Commerce Stock 8

Move stock.

Parameters

\Drupal\commerce\PurchasableEntityInterface $entity: The purchasable entity (most likely a product variation entity).

int $from_location_id: The source location ID.

int $to_location_id: The target location ID.

string $from_zone: The source zone.

string $to_zone: The target zone.

float $quantity: The quantity.

float $unit_cost: The unit cost.

string $currency_code: The currency code.

string $message: The message.

Overrides StockTransactionsInterface::moveStock

File

src/StockServiceManager.php, line 172

Class

StockServiceManager
The stock service manager.

Namespace

Drupal\commerce_stock

Code

public function moveStock(PurchasableEntityInterface $entity, $from_location_id, $to_location_id, $from_zone, $to_zone, $quantity, $unit_cost, $currency_code, $message = NULL) {
  if (is_null($message)) {
    $metadata = [];
  }
  else {
    $metadata = [
      'data' => [
        'message' => $message,
      ],
    ];
  }

  // Make sure quantity is positive.
  $quantity_from = -1 * abs($quantity);
  $quantity_to = abs($quantity);
  $stock_updater = $this
    ->getService($entity)
    ->getStockUpdater();
  $tid = $stock_updater
    ->createTransaction($entity, $from_location_id, $from_zone, $quantity_from, $unit_cost, $currency_code, StockTransactionsInterface::MOVEMENT_FROM, $metadata);

  // The second transaction will point to the first one.
  $metadata['related_tid'] = $tid;
  $stock_updater
    ->createTransaction($entity, $to_location_id, $to_zone, $quantity_to, $unit_cost, $currency_code, StockTransactionsInterface::MOVEMENT_TO, $metadata);
}