AddStockItemsObserver.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\CatalogInventory\Observer;
  7. use Magento\Catalog\Model\Product;
  8. use Magento\Catalog\Model\ResourceModel\Product\Collection;
  9. use Magento\CatalogInventory\Api\StockConfigurationInterface;
  10. use Magento\CatalogInventory\Api\StockItemCriteriaInterfaceFactory;
  11. use Magento\CatalogInventory\Api\StockItemRepositoryInterface;
  12. use Magento\Framework\Event\Observer;
  13. use Magento\Framework\Event\ObserverInterface;
  14. /**
  15. * Add Stock items to product collection.
  16. */
  17. class AddStockItemsObserver implements ObserverInterface
  18. {
  19. /**
  20. * @var StockItemCriteriaInterfaceFactory
  21. */
  22. private $criteriaInterfaceFactory;
  23. /**
  24. * @var StockItemRepositoryInterface
  25. */
  26. private $stockItemRepository;
  27. /**
  28. * @var StockConfigurationInterface
  29. */
  30. private $stockConfiguration;
  31. /**
  32. * AddStockItemsObserver constructor.
  33. *
  34. * @param StockItemCriteriaInterfaceFactory $criteriaInterfaceFactory
  35. * @param StockItemRepositoryInterface $stockItemRepository
  36. * @param StockConfigurationInterface $stockConfiguration
  37. */
  38. public function __construct(
  39. StockItemCriteriaInterfaceFactory $criteriaInterfaceFactory,
  40. StockItemRepositoryInterface $stockItemRepository,
  41. StockConfigurationInterface $stockConfiguration
  42. ) {
  43. $this->criteriaInterfaceFactory = $criteriaInterfaceFactory;
  44. $this->stockItemRepository = $stockItemRepository;
  45. $this->stockConfiguration = $stockConfiguration;
  46. }
  47. /**
  48. * Add stock items to products in collection.
  49. *
  50. * @param Observer $observer
  51. * @return void
  52. */
  53. public function execute(Observer $observer)
  54. {
  55. /** @var Collection $productCollection */
  56. $productCollection = $observer->getData('collection');
  57. $productIds = array_keys($productCollection->getItems());
  58. $criteria = $this->criteriaInterfaceFactory->create();
  59. $criteria->setProductsFilter($productIds);
  60. $criteria->setScopeFilter($this->stockConfiguration->getDefaultScopeId());
  61. $stockItemCollection = $this->stockItemRepository->getList($criteria);
  62. foreach ($stockItemCollection->getItems() as $item) {
  63. /** @var Product $product */
  64. $product = $productCollection->getItemById($item->getProductId());
  65. $productExtension = $product->getExtensionAttributes();
  66. $productExtension->setStockItem($item);
  67. $product->setExtensionAttributes($productExtension);
  68. }
  69. }
  70. }