TotalsInformationManagement.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Checkout\Model;
  7. /**
  8. * Class TotalsInformationManagement
  9. */
  10. class TotalsInformationManagement implements \Magento\Checkout\Api\TotalsInformationManagementInterface
  11. {
  12. /**
  13. * Cart total repository.
  14. *
  15. * @var \Magento\Quote\Api\CartTotalRepositoryInterface
  16. */
  17. protected $cartTotalRepository;
  18. /**
  19. * Quote repository.
  20. *
  21. * @var \Magento\Quote\Api\CartRepositoryInterface
  22. */
  23. protected $cartRepository;
  24. /**
  25. * @param \Magento\Quote\Api\CartRepositoryInterface $cartRepository
  26. * @param \Magento\Quote\Api\CartTotalRepositoryInterface $cartTotalRepository
  27. * @codeCoverageIgnore
  28. */
  29. public function __construct(
  30. \Magento\Quote\Api\CartRepositoryInterface $cartRepository,
  31. \Magento\Quote\Api\CartTotalRepositoryInterface $cartTotalRepository
  32. ) {
  33. $this->cartRepository = $cartRepository;
  34. $this->cartTotalRepository = $cartTotalRepository;
  35. }
  36. /**
  37. * {@inheritDoc}
  38. */
  39. public function calculate(
  40. $cartId,
  41. \Magento\Checkout\Api\Data\TotalsInformationInterface $addressInformation
  42. ) {
  43. /** @var \Magento\Quote\Model\Quote $quote */
  44. $quote = $this->cartRepository->get($cartId);
  45. $this->validateQuote($quote);
  46. if ($quote->getIsVirtual()) {
  47. $quote->setBillingAddress($addressInformation->getAddress());
  48. } else {
  49. $quote->setShippingAddress($addressInformation->getAddress());
  50. $quote->getShippingAddress()->setCollectShippingRates(true)->setShippingMethod(
  51. $addressInformation->getShippingCarrierCode() . '_' . $addressInformation->getShippingMethodCode()
  52. );
  53. }
  54. $quote->collectTotals();
  55. return $this->cartTotalRepository->get($cartId);
  56. }
  57. /**
  58. * @param \Magento\Quote\Model\Quote $quote
  59. * @throws \Magento\Framework\Exception\LocalizedException
  60. * @return void
  61. */
  62. protected function validateQuote(\Magento\Quote\Model\Quote $quote)
  63. {
  64. if ($quote->getItemsCount() === 0) {
  65. throw new \Magento\Framework\Exception\LocalizedException(
  66. __('Totals calculation is not applicable to empty cart')
  67. );
  68. }
  69. }
  70. }