RemoveCouponFromCart.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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\QuoteGraphQl\Model\Resolver;
  8. use Magento\Framework\Exception\CouldNotDeleteException;
  9. use Magento\Framework\Exception\LocalizedException;
  10. use Magento\Framework\Exception\NoSuchEntityException;
  11. use Magento\Framework\GraphQl\Config\Element\Field;
  12. use Magento\Framework\GraphQl\Exception\GraphQlInputException;
  13. use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
  14. use Magento\Framework\GraphQl\Query\ResolverInterface;
  15. use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
  16. use Magento\Quote\Api\CouponManagementInterface;
  17. use Magento\QuoteGraphQl\Model\Cart\GetCartForUser;
  18. /**
  19. * @inheritdoc
  20. */
  21. class RemoveCouponFromCart implements ResolverInterface
  22. {
  23. /**
  24. * @var GetCartForUser
  25. */
  26. private $getCartForUser;
  27. /**
  28. * @var CouponManagementInterface
  29. */
  30. private $couponManagement;
  31. /**
  32. * @param GetCartForUser $getCartForUser
  33. * @param CouponManagementInterface $couponManagement
  34. */
  35. public function __construct(
  36. GetCartForUser $getCartForUser,
  37. CouponManagementInterface $couponManagement
  38. ) {
  39. $this->getCartForUser = $getCartForUser;
  40. $this->couponManagement = $couponManagement;
  41. }
  42. /**
  43. * @inheritdoc
  44. */
  45. public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
  46. {
  47. if (!isset($args['input']['cart_id'])) {
  48. throw new GraphQlInputException(__('Required parameter "cart_id" is missing'));
  49. }
  50. $maskedCartId = $args['input']['cart_id'];
  51. $currentUserId = $context->getUserId();
  52. $cart = $this->getCartForUser->execute($maskedCartId, $currentUserId);
  53. $cartId = $cart->getId();
  54. try {
  55. $this->couponManagement->remove($cartId);
  56. } catch (NoSuchEntityException $exception) {
  57. throw new GraphQlNoSuchEntityException(__($exception->getMessage()));
  58. } catch (CouldNotDeleteException $exception) {
  59. throw new LocalizedException(__($exception->getMessage()));
  60. }
  61. $data['cart']['applied_coupon'] = [
  62. 'code' => '',
  63. ];
  64. return $data;
  65. }
  66. }