ExtractDataFromCart.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\QuoteGraphQl\Model\Cart;
  8. use Magento\Framework\Exception\NoSuchEntityException;
  9. use Magento\Quote\Model\Quote;
  10. use Magento\Quote\Model\Quote\Item as QuoteItem;
  11. use Magento\Quote\Model\QuoteIdToMaskedQuoteIdInterface;
  12. /**
  13. * Extract data from cart
  14. */
  15. class ExtractDataFromCart
  16. {
  17. /**
  18. * @var QuoteIdToMaskedQuoteIdInterface
  19. */
  20. private $quoteIdToMaskedQuoteId;
  21. /**
  22. * @param QuoteIdToMaskedQuoteIdInterface $quoteIdToMaskedQuoteId
  23. */
  24. public function __construct(
  25. QuoteIdToMaskedQuoteIdInterface $quoteIdToMaskedQuoteId
  26. ) {
  27. $this->quoteIdToMaskedQuoteId = $quoteIdToMaskedQuoteId;
  28. }
  29. /**
  30. * Extract data from cart
  31. *
  32. * @param Quote $cart
  33. * @return array
  34. * @throws NoSuchEntityException
  35. */
  36. public function execute(Quote $cart): array
  37. {
  38. $items = [];
  39. /**
  40. * @var QuoteItem $cartItem
  41. */
  42. foreach ($cart->getAllItems() as $cartItem) {
  43. $productData = $cartItem->getProduct()->getData();
  44. $productData['model'] = $cartItem->getProduct();
  45. $items[] = [
  46. 'id' => $cartItem->getItemId(),
  47. 'qty' => $cartItem->getQty(),
  48. 'product' => $productData,
  49. 'model' => $cartItem,
  50. ];
  51. }
  52. $appliedCoupon = $cart->getCouponCode();
  53. return [
  54. 'cart_id' => $this->quoteIdToMaskedQuoteId->execute((int)$cart->getId()),
  55. 'items' => $items,
  56. 'applied_coupon' => $appliedCoupon ? ['code' => $appliedCoupon] : null
  57. ];
  58. }
  59. }