CheapestMethodChooser.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\InstantPurchase\Model\ShippingMethodChoose;
  7. use Magento\Customer\Model\Address;
  8. use Magento\Quote\Api\Data\ShippingMethodInterfaceFactory;
  9. /**
  10. * Creates special shipping method to choose cheapest shipping method after quote creation.
  11. */
  12. class CheapestMethodChooser implements ShippingMethodChooserInterface
  13. {
  14. /**
  15. * @var ShippingMethodInterfaceFactory
  16. */
  17. private $shippingMethodFactory;
  18. /**
  19. * @var CarrierFinder
  20. */
  21. private $carrierFinder;
  22. /**
  23. * CheapestMethodChooser constructor.
  24. * @param ShippingMethodInterfaceFactory $shippingMethodFactory
  25. * @param CarrierFinder $carrierFinder
  26. */
  27. public function __construct(
  28. ShippingMethodInterfaceFactory $shippingMethodFactory,
  29. CarrierFinder $carrierFinder
  30. ) {
  31. $this->shippingMethodFactory = $shippingMethodFactory;
  32. $this->carrierFinder = $carrierFinder;
  33. }
  34. /**
  35. * @inheritdoc
  36. */
  37. public function choose(Address $address)
  38. {
  39. $shippingMethod = $this->shippingMethodFactory->create()
  40. ->setCarrierCode(DeferredShippingMethodChooserInterface::CARRIER)
  41. ->setMethodCode(CheapestMethodDeferredChooser::METHOD_CODE)
  42. ->setMethodTitle(__('Cheapest price'))
  43. ->setAvailable($this->areShippingMethodsAvailable($address));
  44. return $shippingMethod;
  45. }
  46. /**
  47. * Checks if any shipping method available.
  48. *
  49. * @param Address $address
  50. * @return bool
  51. */
  52. private function areShippingMethodsAvailable(Address $address): bool
  53. {
  54. $carriersForAddress = $this->carrierFinder->getCarriersForCustomerAddress($address);
  55. return !empty($carriersForAddress);
  56. }
  57. }