Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CouponManagement.php
Go to the documentation of this file.
1 <?php
8 namespace Magento\Quote\Model;
9 
10 use \Magento\Quote\Api\CouponManagementInterface;
14 
19 {
25  protected $quoteRepository;
26 
32  public function __construct(
34  ) {
35  $this->quoteRepository = $quoteRepository;
36  }
37 
41  public function get($cartId)
42  {
44  $quote = $this->quoteRepository->getActive($cartId);
45  return $quote->getCouponCode();
46  }
47 
51  public function set($cartId, $couponCode)
52  {
54  $quote = $this->quoteRepository->getActive($cartId);
55  if (!$quote->getItemsCount()) {
56  throw new NoSuchEntityException(__('The "%1" Cart doesn\'t contain products.', $cartId));
57  }
58  if (!$quote->getStoreId()) {
59  throw new NoSuchEntityException(__('Cart isn\'t assigned to correct store'));
60  }
61  $quote->getShippingAddress()->setCollectShippingRates(true);
62 
63  try {
64  $quote->setCouponCode($couponCode);
65  $this->quoteRepository->save($quote->collectTotals());
66  } catch (\Exception $e) {
67  throw new CouldNotSaveException(
68  __("The coupon code couldn't be applied. Verify the coupon code and try again.")
69  );
70  }
71  if ($quote->getCouponCode() != $couponCode) {
72  throw new NoSuchEntityException(__("The coupon code isn't valid. Verify the code and try again."));
73  }
74  return true;
75  }
76 
80  public function remove($cartId)
81  {
83  $quote = $this->quoteRepository->getActive($cartId);
84  if (!$quote->getItemsCount()) {
85  throw new NoSuchEntityException(__('The "%1" Cart doesn\'t contain products.', $cartId));
86  }
87  $quote->getShippingAddress()->setCollectShippingRates(true);
88  try {
89  $quote->setCouponCode('');
90  $this->quoteRepository->save($quote->collectTotals());
91  } catch (\Exception $e) {
92  throw new CouldNotDeleteException(
93  __("The coupon code couldn't be deleted. Verify the coupon code and try again.")
94  );
95  }
96  if ($quote->getCouponCode() != '') {
97  throw new CouldNotDeleteException(
98  __("The coupon code couldn't be deleted. Verify the coupon code and try again.")
99  );
100  }
101  return true;
102  }
103 }
$quote
__()
Definition: __.php:13
$cartId
Definition: quote.php:22
__construct(\Magento\Quote\Api\CartRepositoryInterface $quoteRepository)