Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AddStockItemsObserver.php
Go to the documentation of this file.
1 <?php
8 
12 use Magento\CatalogInventory\Api\StockItemCriteriaInterfaceFactory;
16 
21 {
25  private $criteriaInterfaceFactory;
26 
30  private $stockItemRepository;
31 
35  private $stockConfiguration;
36 
44  public function __construct(
45  StockItemCriteriaInterfaceFactory $criteriaInterfaceFactory,
46  StockItemRepositoryInterface $stockItemRepository,
47  StockConfigurationInterface $stockConfiguration
48  ) {
49  $this->criteriaInterfaceFactory = $criteriaInterfaceFactory;
50  $this->stockItemRepository = $stockItemRepository;
51  $this->stockConfiguration = $stockConfiguration;
52  }
53 
60  public function execute(Observer $observer)
61  {
63  $productCollection = $observer->getData('collection');
64  $productIds = array_keys($productCollection->getItems());
65  $criteria = $this->criteriaInterfaceFactory->create();
66  $criteria->setProductsFilter($productIds);
67  $criteria->setScopeFilter($this->stockConfiguration->getDefaultScopeId());
68  $stockItemCollection = $this->stockItemRepository->getList($criteria);
69  foreach ($stockItemCollection->getItems() as $item) {
71  $product = $productCollection->getItemById($item->getProductId());
72  $productExtension = $product->getExtensionAttributes();
73  $productExtension->setStockItem($item);
74  $product->setExtensionAttributes($productExtension);
75  }
76  }
77 }
__construct(StockItemCriteriaInterfaceFactory $criteriaInterfaceFactory, StockItemRepositoryInterface $stockItemRepository, StockConfigurationInterface $stockConfiguration)