Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CartItemPersister.php
Go to the documentation of this file.
1 <?php
8 
16 
18 {
22  private $productRepository;
23 
27  private $cartItemOptionProcessor;
28 
33  public function __construct(
34  ProductRepositoryInterface $productRepository,
35  CartItemOptionsProcessor $cartItemOptionProcessor
36  ) {
37  $this->productRepository = $productRepository;
38  $this->cartItemOptionProcessor = $cartItemOptionProcessor;
39  }
40 
52  {
54  $qty = $item->getQty();
55  if (!is_numeric($qty) || $qty <= 0) {
56  throw InputException::invalidFieldValue('qty', $qty);
57  }
58  $cartId = $item->getQuoteId();
59  $itemId = $item->getItemId();
60  try {
62  if (isset($itemId)) {
63  $currentItem = $quote->getItemById($itemId);
64  if (!$currentItem) {
65  throw new NoSuchEntityException(
66  __('The %1 Cart doesn\'t contain the %2 item.', $cartId, $itemId)
67  );
68  }
69  $productType = $currentItem->getProduct()->getTypeId();
70  $buyRequestData = $this->cartItemOptionProcessor->getBuyRequest($productType, $item);
71  if (is_object($buyRequestData)) {
73  $item = $quote->updateItem($itemId, $buyRequestData);
74  } else {
75  if ($item->getQty() !== $currentItem->getQty()) {
76  $currentItem->setQty($qty);
81  if (!empty($currentItem->getMessage())) {
82  throw new LocalizedException(__($currentItem->getMessage()));
83  }
84  }
85  }
86  } else {
88  $product = $this->productRepository->get($item->getSku());
89  $productType = $product->getTypeId();
90  $item = $quote->addProduct(
91  $product,
92  $this->cartItemOptionProcessor->getBuyRequest($productType, $item)
93  );
94  if (is_string($item)) {
95  throw new LocalizedException(__($item));
96  }
97  }
98  } catch (NoSuchEntityException $e) {
99  throw $e;
100  } catch (LocalizedException $e) {
101  throw $e;
102  } catch (\Exception $e) {
103  throw new CouldNotSaveException(__("The quote couldn't be saved."));
104  }
105  $itemId = $item->getId();
106  foreach ($quote->getAllItems() as $quoteItem) {
108  if ($itemId == $quoteItem->getId()) {
109  $item = $this->cartItemOptionProcessor->addProductOptions($productType, $quoteItem);
110  return $this->cartItemOptionProcessor->applyCustomOptions($item);
111  }
112  }
113  throw new CouldNotSaveException(__("The quote couldn't be saved."));
114  }
115 }
static invalidFieldValue($fieldName, $fieldValue, \Exception $cause=null)
$quote
__()
Definition: __.php:13
$cartId
Definition: quote.php:22
$quoteItem
Definition: quote.php:38
__construct(ProductRepositoryInterface $productRepository, CartItemOptionsProcessor $cartItemOptionProcessor)