Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ProcessInventoryDataObserver.php
Go to the documentation of this file.
1 <?php
7 
13 
23 {
29  private $stockRegistry;
30 
36  public function __construct(
37  \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
38  ) {
39  $this->stockRegistry = $stockRegistry;
40  }
41 
48  public function execute(EventObserver $observer)
49  {
50  $product = $observer->getEvent()->getProduct();
51  $this->processStockData($product);
52  }
53 
63  private function processStockData(Product $product)
64  {
65  $quantityAndStockStatus = $product->getData('quantity_and_stock_status');
66  if (is_array($quantityAndStockStatus)) {
68  $stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId());
69 
70  $quantityAndStockStatus = $this->prepareQuantityAndStockStatus($stockItem, $quantityAndStockStatus);
71 
72  if ($quantityAndStockStatus) {
73  $this->setStockDataToProduct($product, $stockItem, $quantityAndStockStatus);
74  }
75  }
76  }
77 
88  private function prepareQuantityAndStockStatus(StockItemInterface $stockItem, array $quantityAndStockStatus)
89  {
90  $stockItemId = $stockItem->getItemId();
91 
92  if (null !== $stockItemId) {
93  if (isset($quantityAndStockStatus['is_in_stock'])
94  && $stockItem->getIsInStock() == $quantityAndStockStatus['is_in_stock']
95  ) {
96  unset($quantityAndStockStatus['is_in_stock']);
97  }
98  if (array_key_exists('qty', $quantityAndStockStatus)
99  && $stockItem->getQty() == $quantityAndStockStatus['qty']
100  ) {
101  unset($quantityAndStockStatus['qty']);
102  }
103  }
104 
105  if (array_key_exists('qty', $quantityAndStockStatus) && $quantityAndStockStatus['qty'] === '') {
106  $quantityAndStockStatus['qty'] = null;
107  }
108  return $quantityAndStockStatus;
109  }
110 
122  private function setStockDataToProduct(Product $product, Item $stockItem, array $quantityAndStockStatus)
123  {
124  $stockData = array_replace((array)$product->getData('stock_data'), $quantityAndStockStatus);
125  if ($stockItem->hasDataChanges()) {
126  $stockData = array_replace($stockData, $stockItem->getData());
127  }
128  $product->setData('stock_data', $stockData);
129  }
130 }
__construct(\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry)
$stockData
Definition: products.php:27