Here is the sample code:
<?php
namespace SR\MagentoCommunity\Model;
use Magento\InventoryCatalog\Model\GetStockIdForCurrentWebsite;
use Magento\InventorySales\Model\GetProductSalableQty;
use Magento\InventorySalesApi\Model\GetStockItemDataInterface;
class Stock
{
/**
* @var GetProductSalableQty
*/
private $getProductSalableQty;
/**
* @var GetStockIdForCurrentWebsite
*/
private $getStockIdForCurrentWebsite;
/**
* @var GetStockItemDataInterface
*/
private $getStockItemData;
/**
* Stock constructor.
*
* @param GetProductSalableQty $getProductSalableQty
* @param GetStockIdForCurrentWebsite $getStockIdForCurrentWebsite
* @param GetStockItemDataInterface $getStockItemData
*/
public function __construct(
GetProductSalableQty $getProductSalableQty,
GetStockIdForCurrentWebsite $getStockIdForCurrentWebsite,
GetStockItemDataInterface $getStockItemData
) {
$this->getProductSalableQty = $getProductSalableQty;
$this->getStockIdForCurrentWebsite = $getStockIdForCurrentWebsite;
$this->getStockItemData = $getStockItemData;
}
public function getStock($sku)
{
$stockId = $this->getStockIdForCurrentWebsite->execute();
// Actual qty - Reserve Qty - OOS Threshold
$productQtyInStock = $this->getProductSalableQty->execute($sku, $stockId);
echo $productQtyInStock . PHP_EOL;
// Return only qty
$stockItemData = $this->getStockItemData->execute($sku, $stockId);
$qty = $stockItemData[GetStockItemDataInterface::QUANTITY];
echo $qty . PHP_EOL;
}
}
You can get salable qty or total Qty using the above code.