public function loadCheapestShippingMethod(CartOnLoadEvent $event)
{
$cart = $event->getCart();
$cartShippingMethodId = $cart->getShippingMethod();
/**
* We don't have the need to find the cheapest one if the real one is
* already defined
*/
if (null !== $cartShippingMethodId) {
return $this;
}
/**
* If the cart is not associated to any customer, just skip it
*/
if (!$cart->getCustomer() instanceof CustomerInterface) {
return $this;
}
$address = $cart->getDeliveryAddress() instanceof AddressInterface ? $cart->getDeliveryAddress() : $cart->getCustomer()->getAddresses()->first();
/**
* If the user does'nt have any address defined, we cannot approximate
* anything
*/
if (!$address instanceof AddressInterface) {
return $this;
}
$cart->setDeliveryAddress($address);
$validShippingMethods = $this->shippingWrapper->get($cart);
if (!empty($validShippingMethods)) {
$cheapestShippingMethod = $this->shippingResolver->getCheapestShippingMethod($validShippingMethods);
$cart->setCheapestShippingMethod($cheapestShippingMethod->getId());
}
return $this;
}