Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ProcessSourceItemsObserver.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
18 
23 {
27  private $sourceItemsProcessor;
28 
32  private $getSkusByProductIdsInterface;
33 
38  public function __construct(
39  SourceItemsProcessor $sourceItemsProcessor,
40  GetSkusByProductIdsInterface $getSkusByProductIdsInterface
41  ) {
42  $this->sourceItemsProcessor = $sourceItemsProcessor;
43  $this->getSkusByProductIdsInterface = $getSkusByProductIdsInterface;
44  }
45 
51  public function execute(EventObserver $observer)
52  {
54  $product = $observer->getEvent()->getProduct();
55  if ($product->getTypeId() !== Configurable::TYPE_CODE) {
56  return;
57  }
59  $controller = $observer->getEvent()->getController();
60  $configurableMatrix = $controller->getRequest()->getParam('configurable-matrix-serialized', '');
61 
62  if ($configurableMatrix != '') {
63  $productsData = json_decode($configurableMatrix, true);
64  foreach ($productsData as $key => $productData) {
65  if (isset($productData['quantity_per_source'])) {
66  $quantityPerSource = is_array($productData['quantity_per_source'])
67  ? $productData['quantity_per_source']
68  : [];
69 
70  // get sku by child id, because child sku can be changed if product with such sku already exists.
71  $childProductId = $product->getExtensionAttributes()->getConfigurableProductLinks()[$key];
72  $childProductSku = $this->getSkusByProductIdsInterface->execute([$childProductId])[$childProductId];
73  $this->processSourceItems($quantityPerSource, $childProductSku);
74  }
75  }
76  }
77  }
78 
85  private function processSourceItems(array $sourceItems, string $productSku)
86  {
87  foreach ($sourceItems as $key => $sourceItem) {
89  $sourceItems[$key][SourceItemInterface::QUANTITY] = $sourceItems[$key]['quantity_per_source'];
91  = $sourceItems[$key][SourceItemInterface::QUANTITY] > 0 ? 1 : 0;
92  }
93  }
94 
95  $this->sourceItemsProcessor->process($productSku, $sourceItems);
96  }
97 }
$productsData
Definition: products.php:19
$sourceItems
$productData
__construct(SourceItemsProcessor $sourceItemsProcessor, GetSkusByProductIdsInterface $getSkusByProductIdsInterface)
$controller
Definition: info.phtml:14