Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ItemRepository.php
Go to the documentation of this file.
1 <?php
9 
14 
19 {
25  protected $quoteRepository;
26 
32  protected $storeManager;
33 
40 
46  protected $helper;
47 
53  protected $messageFactory;
54 
62  public function __construct(
63  \Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
64  \Magento\Store\Model\StoreManagerInterface $storeManager,
66  \Magento\GiftMessage\Helper\Message $helper,
67  \Magento\GiftMessage\Model\MessageFactory $messageFactory
68  ) {
69  $this->quoteRepository = $quoteRepository;
70  $this->giftMessageManager = $giftMessageManager;
71  $this->storeManager = $storeManager;
72  $this->helper = $helper;
73  $this->messageFactory = $messageFactory;
74  }
75 
79  public function get($cartId, $itemId)
80  {
86  $quote = $this->quoteRepository->getActive($cartId);
87  if (!$item = $quote->getItemById($itemId)) {
88  throw new NoSuchEntityException(
89  __('No item with the provided ID was found in the Cart. Verify the ID and try again.')
90  );
91  };
92  $messageId = $item->getGiftMessageId();
93  if (!$messageId) {
94  return null;
95  }
96 
102  return $this->messageFactory->create()->load($messageId);
103  }
104 
108  public function save($cartId, \Magento\GiftMessage\Api\Data\MessageInterface $giftMessage, $itemId)
109  {
115  $quote = $this->quoteRepository->getActive($cartId);
116 
117  if (!$item = $quote->getItemById($itemId)) {
118  throw new NoSuchEntityException(
119  __(
120  'No product with the "%1" itemId exists in the Cart. Verify your information and try again.',
121  $itemId
122  )
123  );
124  };
125 
126  if ($item->getIsVirtual()) {
127  throw new InvalidTransitionException(__('Gift messages can\'t be used for virtual products.'));
128  }
129  $messageText = $giftMessage->getMessage();
130  if ($messageText && !$this->helper->isMessagesAllowed('items', $quote, $this->storeManager->getStore())) {
131  throw new CouldNotSaveException(__("The gift message isn't available."));
132  }
133  $this->giftMessageManager->setMessage($quote, 'quote_item', $giftMessage, $itemId);
134  return true;
135  }
136 }
__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)
$giftMessage
Definition: items.phtml:47
$quote
__()
Definition: __.php:13
save($cartId, \Magento\GiftMessage\Api\Data\MessageInterface $giftMessage, $itemId)
$cartId
Definition: quote.php:22