CheapestMethodDeferredChooser.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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\Quote\Model\Quote\Address;
  8. use Magento\Quote\Model\Quote\Address\Rate;
  9. /**
  10. * Choose cheapest shipping method for defined quote.
  11. */
  12. class CheapestMethodDeferredChooser implements DeferredShippingMethodChooserInterface
  13. {
  14. const METHOD_CODE = 'cheapest';
  15. /**
  16. * @inheritdoc
  17. */
  18. public function choose(Address $address)
  19. {
  20. $address->setCollectShippingRates(true);
  21. $address->collectShippingRates();
  22. $shippingRates = $address->getAllShippingRates();
  23. if (empty($shippingRates)) {
  24. return null;
  25. }
  26. $cheapestRate = $this->selectCheapestRate($shippingRates);
  27. return $cheapestRate->getCode();
  28. }
  29. /**
  30. * Selects shipping price with minimal price.
  31. *
  32. * @param Rate[] $shippingRates
  33. * @return Rate
  34. */
  35. private function selectCheapestRate(array $shippingRates) : Rate
  36. {
  37. $rate = array_shift($shippingRates);
  38. foreach ($shippingRates as $tmpRate) {
  39. if ($tmpRate->getPrice() < $rate->getPrice()) {
  40. $rate = $tmpRate;
  41. }
  42. }
  43. return $rate;
  44. }
  45. }