Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CartRepository.php
Go to the documentation of this file.
1 <?php
9 
13 
18 {
24  protected $quoteRepository;
25 
31  protected $storeManager;
32 
39 
45  protected $helper;
46 
52  protected $messageFactory;
53 
61  public function __construct(
62  \Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
63  \Magento\Store\Model\StoreManagerInterface $storeManager,
65  \Magento\GiftMessage\Helper\Message $helper,
66  \Magento\GiftMessage\Model\MessageFactory $messageFactory
67  ) {
68  $this->quoteRepository = $quoteRepository;
69  $this->giftMessageManager = $giftMessageManager;
70  $this->storeManager = $storeManager;
71  $this->helper = $helper;
72  $this->messageFactory = $messageFactory;
73  }
74 
78  public function get($cartId)
79  {
81  $quote = $this->quoteRepository->getActive($cartId);
82 
83  $messageId = $quote->getGiftMessageId();
84  if (!$messageId) {
85  return null;
86  }
87 
88  return $this->messageFactory->create()->load($messageId);
89  }
90 
94  public function save($cartId, \Magento\GiftMessage\Api\Data\MessageInterface $giftMessage)
95  {
101  $quote = $this->quoteRepository->getActive($cartId);
102 
103  if (0 == $quote->getItemsCount()) {
104  throw new InputException(__("Gift messages can't be used for an empty cart. Add an item and try again."));
105  }
106 
107  if ($quote->isVirtual()) {
108  throw new InvalidTransitionException(__("Gift messages can't be used for virtual products."));
109  }
110  $messageText = $giftMessage->getMessage();
111  if ($messageText && !$this->helper->isMessagesAllowed('quote', $quote, $this->storeManager->getStore())) {
112  throw new CouldNotSaveException(__("The gift message isn't available."));
113  }
114  $this->giftMessageManager->setMessage($quote, 'quote', $giftMessage);
115  return true;
116  }
117 }
$giftMessage
Definition: items.phtml:47
$quote
__()
Definition: __.php:13
$cartId
Definition: quote.php:22
save($cartId, \Magento\GiftMessage\Api\Data\MessageInterface $giftMessage)
__construct(\Magento\Quote\Api\CartRepositoryInterface $quoteRepository, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\GiftMessage\Model\GiftMessageManager $giftMessageManager, \Magento\GiftMessage\Helper\Message $helper, \Magento\GiftMessage\Model\MessageFactory $messageFactory)