cartItemFactory = $cartItemFactory; $this->cartManager = $cartManager; $this->guestCartRepository = $guestCartRepository; $this->cartRepository = $cartRepository; } /** * Add a product to the cart * * @param ProductInterface $product * @param int $qty Default 1 * @return $this */ public function addItem(ProductInterface $product, $qty = 1) { $cartItem = $this->cartItemFactory->create(); $cartItem->setSku($product->getSku()); $cartItem->setName($product->getName()); $cartItem->setQty($qty); $cartItem->setPrice($product->getPrice()); $cartItem->setProductType($product->getTypeId()); $this->items[] = $cartItem; return $this; } /** * Build the Cart * * @return \Magento\Quote\Api\Data\CartInterface * @throws \Magento\Framework\Exception\CouldNotSaveException * @throws \Magento\Framework\Exception\NoSuchEntityException */ public function create() { $cartId = $this->cartManager->createEmptyCart(); $cart = $this->guestCartRepository->get($cartId); $cart->setItems($this->items); $this->cartRepository->save($cart); return $cart; } /** * Set the cart items * * @param CartInterface[] $items * @return $this */ public function setItems(array $items = []) { $this->items = $items; return $this; } }