Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
GetSourcesByStockIdSkuAndQty.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
10 use Magento\InventorySourceSelectionApi\Api\Data\ItemRequestInterfaceFactory;
11 use Magento\InventorySourceSelectionApi\Api\Data\InventoryRequestInterfaceFactory;
15 
17 {
21  private $itemRequestFactory;
22 
26  private $inventoryRequestFactory;
27 
31  private $sourceSelectionService;
32 
36  private $getDefaultSourceSelectionAlgorithmCode;
37 
41  private $sourceRepository;
42 
46  private $sources = [];
47 
55  public function __construct(
56  ItemRequestInterfaceFactory $itemRequestFactory,
57  InventoryRequestInterfaceFactory $inventoryRequestFactory,
58  SourceSelectionServiceInterface $sourceSelectionService,
59  GetDefaultSourceSelectionAlgorithmCodeInterface $getDefaultSourceSelectionAlgorithmCode,
60  SourceRepositoryInterface $sourceRepository
61  ) {
62  $this->itemRequestFactory = $itemRequestFactory;
63  $this->inventoryRequestFactory = $inventoryRequestFactory;
64  $this->sourceSelectionService = $sourceSelectionService;
65  $this->getDefaultSourceSelectionAlgorithmCode = $getDefaultSourceSelectionAlgorithmCode;
66  $this->sourceRepository = $sourceRepository;
67  }
68 
76  public function execute(int $stockId, string $sku, float $qty): array
77  {
78  $algorithmCode = $this->getDefaultSourceSelectionAlgorithmCode->execute();
79 
80  $requestItem = $this->itemRequestFactory->create([
81  'sku' => $sku,
82  'qty' => $qty
83  ]);
84  $inventoryRequest = $this->inventoryRequestFactory->create([
85  'stockId' => $stockId,
86  'items' => [$requestItem]
87  ]);
88  $sourceSelectionResult = $this->sourceSelectionService->execute(
89  $inventoryRequest,
90  $algorithmCode
91  );
92  $result = [];
93  foreach ($sourceSelectionResult->getSourceSelectionItems() as $item) {
94  $sourceCode = $item->getSourceCode();
95  $result[] = [
96  'sourceName' => $this->getSourceName($sourceCode),
97  'sourceCode' => $sourceCode,
98  'qtyAvailable' => $item->getQtyAvailable(),
99  'qtyToDeduct' => $item->getQtyToDeduct()
100  ];
101  }
102 
103  return $result;
104  }
105 
113  private function getSourceName(string $sourceCode): string
114  {
115  if (!isset($this->sources[$sourceCode])) {
116  $this->sources[$sourceCode] = $this->sourceRepository->get($sourceCode)->getName();
117  }
118 
119  return $this->sources[$sourceCode];
120  }
121 }
__construct(ItemRequestInterfaceFactory $itemRequestFactory, InventoryRequestInterfaceFactory $inventoryRequestFactory, SourceSelectionServiceInterface $sourceSelectionService, GetDefaultSourceSelectionAlgorithmCodeInterface $getDefaultSourceSelectionAlgorithmCode, SourceRepositoryInterface $sourceRepository)
$sourceCode
Definition: inventory.phtml:11
$sourceRepository
Definition: source.php:20