StockStatusProvider.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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\CatalogInventoryGraphQl\Model\Resolver;
  8. use Magento\Catalog\Api\Data\ProductInterface;
  9. use Magento\CatalogInventory\Api\Data\StockStatusInterface;
  10. use Magento\CatalogInventory\Api\StockStatusRepositoryInterface;
  11. use Magento\Framework\Exception\LocalizedException;
  12. use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
  13. use Magento\Framework\GraphQl\Config\Element\Field;
  14. use Magento\Framework\GraphQl\Query\ResolverInterface;
  15. /**
  16. * @inheritdoc
  17. */
  18. class StockStatusProvider implements ResolverInterface
  19. {
  20. /**
  21. * @var StockStatusRepositoryInterface
  22. */
  23. private $stockStatusRepository;
  24. /**
  25. * @param StockStatusRepositoryInterface $stockStatusRepository
  26. */
  27. public function __construct(StockStatusRepositoryInterface $stockStatusRepository)
  28. {
  29. $this->stockStatusRepository = $stockStatusRepository;
  30. }
  31. /**
  32. * @inheritdoc
  33. */
  34. public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
  35. {
  36. if (!array_key_exists('model', $value) || !$value['model'] instanceof ProductInterface) {
  37. throw new LocalizedException(__('"model" value should be specified'));
  38. }
  39. /* @var $product ProductInterface */
  40. $product = $value['model'];
  41. $stockStatus = $this->stockStatusRepository->get($product->getId());
  42. $productStockStatus = (int)$stockStatus->getStockStatus();
  43. return $productStockStatus === StockStatusInterface::STATUS_IN_STOCK ? 'IN_STOCK' : 'OUT_OF_STOCK';
  44. }
  45. }