Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ShippingConfiguration.php
Go to the documentation of this file.
1 <?php
7 
14 
22 {
26  private $deferredShippingMethodChooserPool;
27 
32  public function __construct(
33  DeferredShippingMethodChooserPool $deferredShippingMethodChooserPool
34  ) {
35  $this->deferredShippingMethodChooserPool = $deferredShippingMethodChooserPool;
36  }
37 
47  public function configureShippingMethod(
48  Quote $quote,
50  ): Quote {
51  if ($quote->isVirtual()) {
52  return $quote;
53  }
54 
55  $shippingAddress = $quote->getShippingAddress();
56  $shippingMethodCode = $this->getShippingMethodCodeToUse($shippingAddress, $shippingMethod);
57  $shippingAddress->setShippingMethod($shippingMethodCode);
58 
59  return $quote;
60  }
61 
70  private function getShippingMethodCodeToUse(
73  ): string {
75  return $this->resolveDeferredShippingMethodChoose($address, $shippingMethod);
76  } else {
77  return $this->getCorrespondingShippingRateCode($address, $shippingMethod);
78  }
79  }
80 
89  private function getCorrespondingShippingRateCode(
90  Address $address,
91  ShippingMethodInterface $shippingMethod
92  ): string {
93  $address->setCollectShippingRates(true);
94  $address->collectShippingRates();
95  $shippingRates = $address->getAllShippingRates();
96  foreach ($shippingRates as $shippingRate) {
97  if ($shippingRate->getCarrier() === $shippingMethod->getCarrierCode()
98  &&
99  $shippingRate->getMethod() === $shippingMethod->getMethodCode()
100  ) {
101  return $shippingRate->getCode();
102  }
103  }
104  throw new LocalizedException(__('Specified shipping method is not available.'));
105  }
106 
115  private function resolveDeferredShippingMethodChoose(
116  Address $address,
117  ShippingMethodInterface $shippingMethod
118  ): string {
119  $deferredShippingMethodChooser = $this->deferredShippingMethodChooserPool->get(
120  $shippingMethod->getMethodCode()
121  );
122 
123  $shippingMethodCode = $deferredShippingMethodChooser->choose($address);
124  if (empty($shippingMethodCode)) {
125  throw new LocalizedException(__('Appropriate shipping method is not available.'));
126  }
127 
128  return $shippingMethodCode;
129  }
130 }
configureShippingMethod(Quote $quote, ShippingMethodInterface $shippingMethod)
$quote
$shippingAddress
Definition: order.php:40
__()
Definition: __.php:13
$address
Definition: customer.php:38
__construct(DeferredShippingMethodChooserPool $deferredShippingMethodChooserPool)
$shippingMethod
Definition: popup.phtml:12