/** * Create customerAddressDataObject and save it in the Model\Quote so that it can be used to persist later. * * @param CustomerDataObject $customerDataObject * @param \Magento\Sales\Model\Quote\Address $quoteCustomerAddress * @return void * @throws \InvalidArgumentException */ protected function _prepareCustomerAddress($customerDataObject, $quoteCustomerAddress) { // Possible that customerId is null for new customers $customerId = $customerDataObject->getId(); $quoteCustomerAddress->setCustomerId($customerId); $customerAddressDataObject = $quoteCustomerAddress->exportCustomerAddressData(); $quoteAddressId = $quoteCustomerAddress->getCustomerAddressId(); $addressType = $quoteCustomerAddress->getAddressType(); if ($quoteAddressId) { /** Update existing address */ $existingAddressDataObject = $this->_customerAddressService->getAddress($quoteAddressId); /** Update customer address data */ $customerAddressDataObject = $this->_customerAddressBuilder->mergeDataObjects($existingAddressDataObject, $customerAddressDataObject); } elseif ($addressType == CustomerAddressDataObject::ADDRESS_TYPE_SHIPPING) { try { $billingAddressDataObject = $this->_customerAddressService->getDefaultBillingAddress($customerId); } catch (\Exception $e) { /** Billing address does not exist. */ } $isShippingAsBilling = $quoteCustomerAddress->getSameAsBilling(); if (isset($billingAddressDataObject) && $isShippingAsBilling) { /** Set existing billing address as default shipping */ $customerAddressDataObject = $this->_customerAddressBuilder->populate($billingAddressDataObject)->setDefaultShipping(true)->create(); } } switch ($addressType) { case CustomerAddressDataObject::ADDRESS_TYPE_BILLING: if (is_null($customerDataObject->getDefaultBilling())) { $customerAddressDataObject = $this->_customerAddressBuilder->populate($customerAddressDataObject)->setDefaultBilling(true)->create(); } break; case CustomerAddressDataObject::ADDRESS_TYPE_SHIPPING: if (is_null($customerDataObject->getDefaultShipping())) { $customerAddressDataObject = $this->_customerAddressBuilder->populate($customerAddressDataObject)->setDefaultShipping(true)->create(); } break; default: throw new \InvalidArgumentException('Customer address type is invalid.'); } $this->getQuote()->addCustomerAddressData($customerAddressDataObject); }