ParamOverriderCartId.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Quote\Model\Webapi;
  7. use Magento\Authorization\Model\UserContextInterface;
  8. use Magento\Framework\Webapi\Rest\Request\ParamOverriderInterface;
  9. use Magento\Framework\Exception\NoSuchEntityException;
  10. use Magento\Quote\Api\CartManagementInterface;
  11. /**
  12. * Replaces a "%cart_id%" value with the current authenticated customer's cart
  13. */
  14. class ParamOverriderCartId implements ParamOverriderInterface
  15. {
  16. /**
  17. * @var UserContextInterface
  18. */
  19. private $userContext;
  20. /**
  21. * @var CartManagementInterface
  22. */
  23. private $cartManagement;
  24. /**
  25. * Constructs an object to override the cart ID parameter on a request.
  26. *
  27. * @param UserContextInterface $userContext
  28. * @param CartManagementInterface $cartManagement
  29. */
  30. public function __construct(
  31. UserContextInterface $userContext,
  32. CartManagementInterface $cartManagement
  33. ) {
  34. $this->userContext = $userContext;
  35. $this->cartManagement = $cartManagement;
  36. }
  37. /**
  38. * {@inheritDoc}
  39. */
  40. public function getOverriddenValue()
  41. {
  42. try {
  43. if ($this->userContext->getUserType() === UserContextInterface::USER_TYPE_CUSTOMER) {
  44. $customerId = $this->userContext->getUserId();
  45. /** @var \Magento\Quote\Api\Data\CartInterface */
  46. $cart = $this->cartManagement->getCartForCustomer($customerId);
  47. if ($cart) {
  48. return $cart->getId();
  49. }
  50. }
  51. } catch (NoSuchEntityException $e) {
  52. throw new NoSuchEntityException(__('Current customer does not have an active cart.'));
  53. }
  54. return null;
  55. }
  56. }