StockItemValidator.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\CatalogInventory\Model;
  7. use Magento\Catalog\Api\Data\ProductInterface;
  8. use Magento\CatalogInventory\Api\Data\StockItemInterface;
  9. use Magento\CatalogInventory\Api\StockConfigurationInterface;
  10. use Magento\CatalogInventory\Api\StockRegistryInterface;
  11. use Magento\Framework\Exception\LocalizedException;
  12. /**
  13. * StockItemValidator
  14. */
  15. class StockItemValidator
  16. {
  17. /**
  18. * @var StockConfigurationInterface
  19. */
  20. private $stockConfiguration;
  21. /**
  22. * @var StockRegistryInterface
  23. */
  24. private $stockRegistry;
  25. /**
  26. * @param StockConfigurationInterface $stockConfiguration
  27. * @param StockRegistryInterface $stockRegistry
  28. */
  29. public function __construct(
  30. StockConfigurationInterface $stockConfiguration,
  31. StockRegistryInterface $stockRegistry
  32. ) {
  33. $this->stockConfiguration = $stockConfiguration;
  34. $this->stockRegistry = $stockRegistry;
  35. }
  36. /**
  37. * Validate Stock item
  38. *
  39. * @param ProductInterface $product
  40. * @param StockItemInterface $stockItem
  41. * @throws LocalizedException
  42. * @return void
  43. */
  44. public function validate(ProductInterface $product, StockItemInterface $stockItem)
  45. {
  46. $defaultScopeId = $this->stockConfiguration->getDefaultScopeId();
  47. $defaultStockId = $this->stockRegistry->getStock($defaultScopeId)->getStockId();
  48. $stockId = $stockItem->getStockId();
  49. if ($stockId !== null && $stockId != $defaultStockId) {
  50. throw new LocalizedException(
  51. __(
  52. 'The "%1" value is invalid for stock ID. Enter stock with a default value of %2 to try again.',
  53. $stockId,
  54. $defaultStockId
  55. )
  56. );
  57. }
  58. $stockItemId = $stockItem->getItemId();
  59. if ($stockItemId !== null && (!is_numeric($stockItemId) || $stockItemId <= 0)) {
  60. throw new LocalizedException(
  61. __(
  62. 'The "%1" value is invalid for stock item ID. '
  63. . 'Enter either zero or a number than zero to try again.',
  64. $stockItemId
  65. )
  66. );
  67. }
  68. $defaultStockItemId = $this->stockRegistry->getStockItem($product->getId())->getItemId();
  69. if ($defaultStockItemId && $stockItemId !== null && $defaultStockItemId != $stockItemId) {
  70. throw new LocalizedException(
  71. __(
  72. 'The "%1" value is invalid for stock item ID. '
  73. . 'Use the stock item ID\'s assigned "%2" value and try again.',
  74. $stockItemId,
  75. $defaultStockItemId
  76. )
  77. );
  78. }
  79. }
  80. }