GetCartForUser.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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\Framework\GraphQl\Exception\GraphQlAuthorizationException;
  10. use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
  11. use Magento\Quote\Api\CartRepositoryInterface;
  12. use Magento\Quote\Model\MaskedQuoteIdToQuoteIdInterface;
  13. use Magento\Quote\Model\Quote;
  14. /**
  15. * Get cart
  16. */
  17. class GetCartForUser
  18. {
  19. /**
  20. * @var MaskedQuoteIdToQuoteIdInterface
  21. */
  22. private $maskedQuoteIdToQuoteId;
  23. /**
  24. * @var CartRepositoryInterface
  25. */
  26. private $cartRepository;
  27. /**
  28. * @param MaskedQuoteIdToQuoteIdInterface $maskedQuoteIdToQuoteId
  29. * @param CartRepositoryInterface $cartRepository
  30. */
  31. public function __construct(
  32. MaskedQuoteIdToQuoteIdInterface $maskedQuoteIdToQuoteId,
  33. CartRepositoryInterface $cartRepository
  34. ) {
  35. $this->maskedQuoteIdToQuoteId = $maskedQuoteIdToQuoteId;
  36. $this->cartRepository = $cartRepository;
  37. }
  38. /**
  39. * Get cart for user
  40. *
  41. * @param string $cartHash
  42. * @param int|null $userId
  43. * @return Quote
  44. * @throws GraphQlAuthorizationException
  45. * @throws GraphQlNoSuchEntityException
  46. */
  47. public function execute(string $cartHash, ?int $userId): Quote
  48. {
  49. try {
  50. $cartId = $this->maskedQuoteIdToQuoteId->execute($cartHash);
  51. } catch (NoSuchEntityException $exception) {
  52. throw new GraphQlNoSuchEntityException(
  53. __('Could not find a cart with ID "%masked_cart_id"', ['masked_cart_id' => $cartHash])
  54. );
  55. }
  56. try {
  57. /** @var Quote $cart */
  58. $cart = $this->cartRepository->get($cartId);
  59. } catch (NoSuchEntityException $e) {
  60. throw new GraphQlNoSuchEntityException(
  61. __('Could not find a cart with ID "%masked_cart_id"', ['masked_cart_id' => $cartHash])
  62. );
  63. }
  64. $customerId = (int)$cart->getCustomerId();
  65. /* Guest cart, allow operations */
  66. if (!$customerId) {
  67. return $cart;
  68. }
  69. if ($customerId !== $userId) {
  70. throw new GraphQlAuthorizationException(
  71. __(
  72. 'The current user cannot perform operations on cart "%masked_cart_id"',
  73. ['masked_cart_id' => $cartHash]
  74. )
  75. );
  76. }
  77. return $cart;
  78. }
  79. }