Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Repository.php
Go to the documentation of this file.
1 <?php
9 
13 
15 {
21  protected $quoteRepository;
22 
28  protected $productRepository;
29 
33  protected $itemDataFactory;
34 
39 
43  private $cartItemOptionsProcessor;
44 
51  public function __construct(
54  \Magento\Quote\Api\Data\CartItemInterfaceFactory $itemDataFactory,
55  array $cartItemProcessors = []
56  ) {
57  $this->quoteRepository = $quoteRepository;
58  $this->productRepository = $productRepository;
59  $this->itemDataFactory = $itemDataFactory;
60  $this->cartItemProcessors = $cartItemProcessors;
61  }
62 
66  public function getList($cartId)
67  {
68  $output = [];
70  $quote = $this->quoteRepository->getActive($cartId);
71 
73  foreach ($quote->getAllVisibleItems() as $item) {
74  $item = $this->getCartItemOptionsProcessor()->addProductOptions($item->getProductType(), $item);
75  $output[] = $this->getCartItemOptionsProcessor()->applyCustomOptions($item);
76  }
77  return $output;
78  }
79 
83  public function save(\Magento\Quote\Api\Data\CartItemInterface $cartItem)
84  {
86  $cartId = $cartItem->getQuoteId();
87  $quote = $this->quoteRepository->getActive($cartId);
88 
89  $quoteItems = $quote->getItems();
90  $quoteItems[] = $cartItem;
91  $quote->setItems($quoteItems);
92  $this->quoteRepository->save($quote);
93  $quote->collectTotals();
94  return $quote->getLastAddedItem();
95  }
96 
100  public function deleteById($cartId, $itemId)
101  {
103  $quote = $this->quoteRepository->getActive($cartId);
104  $quoteItem = $quote->getItemById($itemId);
105  if (!$quoteItem) {
106  throw new NoSuchEntityException(
107  __('The %1 Cart doesn\'t contain the %2 item.', $cartId, $itemId)
108  );
109  }
110  try {
111  $quote->removeItem($itemId);
112  $this->quoteRepository->save($quote);
113  } catch (\Exception $e) {
114  throw new CouldNotSaveException(__("The item couldn't be removed from the quote."));
115  }
116 
117  return true;
118  }
119 
124  private function getCartItemOptionsProcessor()
125  {
126  if (!$this->cartItemOptionsProcessor instanceof CartItemOptionsProcessor) {
127  $this->cartItemOptionsProcessor = ObjectManager::getInstance()->get(CartItemOptionsProcessor::class);
128  }
129 
130  return $this->cartItemOptionsProcessor;
131  }
132 }
save(\Magento\Quote\Api\Data\CartItemInterface $cartItem)
$quote
__()
Definition: __.php:13
$cartId
Definition: quote.php:22
$quoteItem
Definition: quote.php:38
__construct(\Magento\Quote\Api\CartRepositoryInterface $quoteRepository, \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, \Magento\Quote\Api\Data\CartItemInterfaceFactory $itemDataFactory, array $cartItemProcessors=[])
Definition: Repository.php:51