DeleteById.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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\Inventory\Model\Stock\Command;
  8. use Magento\Framework\Exception\CouldNotDeleteException;
  9. use Magento\Framework\Exception\NoSuchEntityException;
  10. use Magento\Inventory\Model\ResourceModel\Stock as StockResourceModel;
  11. use Magento\InventoryApi\Api\Data\StockInterface;
  12. use Magento\InventoryApi\Api\Data\StockInterfaceFactory;
  13. use Psr\Log\LoggerInterface;
  14. /**
  15. * @inheritdoc
  16. */
  17. class DeleteById implements DeleteByIdInterface
  18. {
  19. /**
  20. * @var StockResourceModel
  21. */
  22. private $stockResource;
  23. /**
  24. * @var StockInterfaceFactory
  25. */
  26. private $stockFactory;
  27. /**
  28. * @var LoggerInterface
  29. */
  30. private $logger;
  31. /**
  32. * @param StockResourceModel $stockResource
  33. * @param StockInterfaceFactory $stockFactory
  34. * @param LoggerInterface $logger
  35. */
  36. public function __construct(
  37. StockResourceModel $stockResource,
  38. StockInterfaceFactory $stockFactory,
  39. LoggerInterface $logger
  40. ) {
  41. $this->stockResource = $stockResource;
  42. $this->stockFactory = $stockFactory;
  43. $this->logger = $logger;
  44. }
  45. /**
  46. * @inheritdoc
  47. */
  48. public function execute(int $stockId)
  49. {
  50. /** @var StockInterface $stock */
  51. $stock = $this->stockFactory->create();
  52. $this->stockResource->load($stock, $stockId, StockInterface::STOCK_ID);
  53. if (null === $stock->getStockId()) {
  54. throw new NoSuchEntityException(
  55. __(
  56. 'There is no stock with "%fieldValue" for "%fieldName". Verify and try again.',
  57. [
  58. 'fieldName' => StockInterface::STOCK_ID,
  59. 'fieldValue' => $stockId
  60. ]
  61. )
  62. );
  63. }
  64. try {
  65. $this->stockResource->delete($stock);
  66. } catch (\Exception $e) {
  67. $this->logger->error($e->getMessage());
  68. throw new CouldNotDeleteException(__('Could not delete Stock'), $e);
  69. }
  70. }
  71. }