命名空间vendor \ module \ Helper;
类数据扩展\ Magento \ Framework \ App \ Helper \ AbstractHelper {
protected $_stockItemRepository;
protected $_scopeConfig;
protected $_storeScope;
public function __construct(\Magento\CatalogInventory\Model\Stock\StockItemRepository $_stockItemRepository, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig)
{
$this->_stockItemRepository = $_stockItemRepository;
$this->_scopeConfig = $scopeConfig;
$this->_storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
}
public function getIdsToLastStock($ids){
if($this->_scopeConfig->getValue('module/vendor_module/active',$this->_storeScope)==1) {
$products = array();
$productIds = array();
foreach ($ids as $id) {
try {
$stockItem = $this->_stockItemRepository->get($id);
$products[] = array('id' => $id, 'stock' => $this->checkIfAvailableInStock($stockItem));
} catch (\Exception $ex) {
$products[] = array('id' => $id, 'stock' => 0);
}
}
if (count($products) > 0) {
foreach ($products as $id => $value) {
$names[$id] = $value['stock'];
}
$keys = array_keys($products);
array_multisort(
$names, SORT_ASC, SORT_NUMERIC, $products, $keys
);
$result = array_combine($keys, $products);
foreach ($result as $product) {
$productIds[] = intval($product['id']);
}
return $productIds;
} else {
return $ids;
}
}
return $ids;
}
private function checkIfAvailableInStock($item){
if($item->getIsInStock()){
if($item->getQty()>0)
return 0;
}
return 1;
}
}