Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
StockSourceLinkProcessor.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
13 use Magento\InventoryApi\Api\Data\StockSourceLinkInterfaceFactory;
18 
24 {
28  private $searchCriteriaBuilder;
29 
33  private $stockSourceLinkFactory;
34 
38  private $stockSourceLinksSave;
39 
43  private $stockSourceLinksDelete;
44 
48  private $getStockSourceLinks;
49 
53  private $dataObjectHelper;
54 
63  public function __construct(
64  SearchCriteriaBuilder $searchCriteriaBuilder,
65  StockSourceLinkInterfaceFactory $stockSourceLinkFactory,
66  StockSourceLinksSaveInterface $stockSourceLinksSave,
67  StockSourceLinksDeleteInterface $stockSourceLinksDelete,
68  GetStockSourceLinksInterface $getStockSourceLinks,
69  DataObjectHelper $dataObjectHelper
70  ) {
71  $this->searchCriteriaBuilder = $searchCriteriaBuilder;
72  $this->stockSourceLinkFactory = $stockSourceLinkFactory;
73  $this->stockSourceLinksSave = $stockSourceLinksSave;
74  $this->stockSourceLinksDelete = $stockSourceLinksDelete;
75  $this->getStockSourceLinks = $getStockSourceLinks;
76  $this->dataObjectHelper = $dataObjectHelper;
77  }
78 
85  public function process(int $stockId, array $linksData)
86  {
87  $linksForDelete = $this->getAssignedLinks($stockId);
88  $linksForSave = [];
89 
90  foreach ($linksData as $linkData) {
92 
93  if (isset($linksForDelete[$sourceCode])) {
94  $link = $linksForDelete[$sourceCode];
95  } else {
97  $link = $this->stockSourceLinkFactory->create();
98  }
99 
101  $this->dataObjectHelper->populateWithArray($link, $linkData, StockSourceLinkInterface::class);
102 
103  $linksForSave[] = $link;
104  unset($linksForDelete[$sourceCode]);
105  }
106 
107  if (count($linksForSave) > 0) {
108  $this->stockSourceLinksSave->execute($linksForSave);
109  }
110  if (count($linksForDelete) > 0) {
111  $this->stockSourceLinksDelete->execute($linksForDelete);
112  }
113  }
114 
121  private function getAssignedLinks(int $stockId): array
122  {
123  $searchCriteria = $this->searchCriteriaBuilder
124  ->addFilter(StockSourceLinkInterface::STOCK_ID, $stockId)
125  ->create();
126 
127  $result = [];
128  foreach ($this->getStockSourceLinks->execute($searchCriteria)->getItems() as $link) {
129  $result[$link->getSourceCode()] = $link;
130  }
131  return $result;
132  }
133 }
$searchCriteria
$sourceCode
Definition: inventory.phtml:11
$searchCriteriaBuilder