CheckItemsQuantity.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\InventorySales\Model;
  8. use Magento\Framework\Exception\LocalizedException;
  9. use Magento\InventorySalesApi\Api\IsProductSalableForRequestedQtyInterface;
  10. use Magento\InventorySalesApi\Api\Data\ProductSalableResultInterface;
  11. use Magento\InventorySalesApi\Api\Data\ProductSalabilityErrorInterface;
  12. class CheckItemsQuantity
  13. {
  14. /**
  15. * @var IsProductSalableForRequestedQtyInterface
  16. */
  17. private $isProductSalableForRequestedQty;
  18. /**
  19. * @param IsProductSalableForRequestedQtyInterface $isProductSalableForRequestedQty
  20. */
  21. public function __construct(
  22. IsProductSalableForRequestedQtyInterface $isProductSalableForRequestedQty
  23. ) {
  24. $this->isProductSalableForRequestedQty = $isProductSalableForRequestedQty;
  25. }
  26. /**
  27. * Check whether all items salable
  28. *
  29. * @param array $items [['sku' => 'qty'], ...]
  30. * @param int $stockId
  31. * @return void
  32. * @throws LocalizedException
  33. */
  34. public function execute(array $items, int $stockId) : void
  35. {
  36. foreach ($items as $sku => $qty) {
  37. /** @var ProductSalableResultInterface $isSalable */
  38. $isSalable = $this->isProductSalableForRequestedQty->execute((string)$sku, $stockId, (float)$qty);
  39. if (false === $isSalable->isSalable()) {
  40. $errors = $isSalable->getErrors();
  41. /** @var ProductSalabilityErrorInterface $errorMessage */
  42. $errorMessage = array_pop($errors);
  43. throw new LocalizedException(__($errorMessage->getMessage()));
  44. }
  45. }
  46. }
  47. }