ShippingProcessor.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Quote\Model\Quote\ShippingAssignment;
  7. use Magento\Quote\Api\Data\CartInterface;
  8. use Magento\Quote\Api\Data\ShippingInterface;
  9. use Magento\Quote\Model\ShippingFactory;
  10. use Magento\Quote\Model\ShippingAddressManagement;
  11. use Magento\Quote\Model\ShippingMethodManagement;
  12. class ShippingProcessor
  13. {
  14. /**
  15. * @var ShippingFactory
  16. */
  17. private $shippingFactory;
  18. /**
  19. * @var ShippingAddressManagement
  20. */
  21. private $shippingAddressManagement;
  22. /**
  23. * @var ShippingMethodManagement
  24. */
  25. private $shippingMethodManagement;
  26. /**
  27. * @param ShippingFactory $shippingFactory
  28. * @param ShippingAddressManagement $shippingAddressManagement
  29. * @param ShippingMethodManagement $shippingMethodManagement
  30. */
  31. public function __construct(
  32. ShippingFactory $shippingFactory,
  33. ShippingAddressManagement $shippingAddressManagement,
  34. ShippingMethodManagement $shippingMethodManagement
  35. ) {
  36. $this->shippingFactory = $shippingFactory;
  37. $this->shippingAddressManagement = $shippingAddressManagement;
  38. $this->shippingMethodManagement = $shippingMethodManagement;
  39. }
  40. /**
  41. * @param \Magento\Quote\Api\Data\AddressInterface $shippingAddress
  42. * @return \Magento\Quote\Api\Data\ShippingInterface
  43. */
  44. public function create(\Magento\Quote\Api\Data\AddressInterface $shippingAddress)
  45. {
  46. /** @var \Magento\Quote\Api\Data\ShippingInterface $shipping */
  47. $shipping = $this->shippingFactory->create();
  48. $shipping->setMethod($shippingAddress->getShippingMethod());
  49. $shipping->setAddress($shippingAddress);
  50. return $shipping;
  51. }
  52. /**
  53. * @param ShippingInterface $shipping
  54. * @param CartInterface $quote
  55. * @return void
  56. */
  57. public function save(ShippingInterface $shipping, CartInterface $quote)
  58. {
  59. $this->shippingAddressManagement->assign($quote->getId(), $shipping->getAddress());
  60. if (!empty($shipping->getMethod()) && $quote->getItemsCount() > 0) {
  61. $nameComponents = explode('_', $shipping->getMethod());
  62. $carrierCode = array_shift($nameComponents);
  63. // carrier method code can contains more one name component
  64. $methodCode = implode('_', $nameComponents);
  65. $this->shippingMethodManagement->apply($quote->getId(), $carrierCode, $methodCode);
  66. }
  67. }
  68. }