ProductBundleStockProxy.php in Commerce Product Bundle 8
File
modules/commerce_product_bundle_stock/src/ProductBundleStockProxy.php
View source
<?php
namespace Drupal\commerce_product_bundle_stock;
use Drupal\commerce\PurchasableEntityInterface;
use Drupal\commerce_product_bundle\Entity\BundleInterface;
use Drupal\commerce_stock\StockCheckInterface;
use Drupal\commerce_stock\StockServiceManagerInterface;
use Drupal\commerce_stock\StockUpdateInterface;
class ProductBundleStockProxy implements StockCheckInterface, StockUpdateInterface {
protected $stockServiceManager;
public function __construct(StockServiceManagerInterface $stock_service_manager) {
$this->stockServiceManager = $stock_service_manager;
}
public function createTransaction(PurchasableEntityInterface $bundle, $location_id, $zone, $quantity, $unit_cost, $currency_code, $transaction_type_id, array $metadata) {
foreach ($bundle
->getBundleItems() as $item) {
$entity = $item
->getCurrentVariation();
$service = $this->stockServiceManager
->getService($entity);
$updater = $service
->getStockUpdater();
$item_quantity = $quantity * $item
->getQuantity();
$updater
->createTransaction($entity, $location_id, $zone, $item_quantity, $unit_cost, $currency_code, $transaction_type_id, $metadata);
}
}
public function getTotalStockLevel(PurchasableEntityInterface $bundle, array $locations) {
$levels = array_map(function ($bundleItem) use ($bundle, $locations) {
$quantity = $bundleItem
->getQuantity() ?: 1;
$entity = $bundleItem
->getCurrentVariation();
$service = $this->stockServiceManager
->getService($entity);
$level = $service
->getStockChecker()
->getTotalStockLevel($entity, $locations);
return floor($level / $quantity);
}, $bundle
->getBundleItems());
return min($levels);
}
public function getIsInStock(PurchasableEntityInterface $bundle, array $locations) {
foreach ($this
->getAllPurchasableEntities($bundle) as $entity) {
$service = $this->stockServiceManager
->getService($entity);
$checker = $service
->getStockChecker();
if (!$checker
->getIsInStock($entity, $locations)) {
return FALSE;
}
}
return TRUE;
}
public function getIsAlwaysInStock(PurchasableEntityInterface $bundle) {
$entities = $this
->getAllPurchasableEntities($bundle);
foreach ($entities as $entity) {
xdebug_break();
$service = $this->stockServiceManager
->getService($entity);
$checker = $service
->getStockChecker();
if (!$checker
->getIsAlwaysInStock($entity)) {
return FALSE;
}
}
return TRUE;
}
public function getIsStockManaged(PurchasableEntityInterface $bundle) {
return TRUE;
}
public function getLocationList($return_active_only = TRUE) {
$services = $this->stockServiceManager
->listServices();
$locations = [];
foreach ($services as $service) {
$locations += $service
->getStockChecker()
->getLocationList();
}
return $locations;
}
protected function getAllPurchasableEntities(BundleInterface $product_bundle) {
return array_map(function ($item) {
return $item
->getCurrentVariation();
}, $product_bundle
->getBundleItems());
}
}