1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sales\Model\ResourceModel\Order\Handler;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\ResourceModel\Attribute;
/**
* Class Address
*/
class Address
{
/**
* @var Attribute
*/
protected $attribute;
/**
* @param Attribute $attribute
*/
public function __construct(
Attribute $attribute
) {
$this->attribute = $attribute;
}
/**
* Remove empty addresses from order
*
* @param Order $order
* @return $this
*/
public function removeEmptyAddresses(Order $order)
{
if ($order->hasBillingAddressId() && $order->getBillingAddressId() === null) {
$order->unsBillingAddressId();
}
if ($order->hasShippingAddressId() && $order->getShippingAddressId() === null) {
$order->unsShippingAddressId();
}
return $this;
}
/**
* Process addresses saving
*
* @param Order $order
* @return $this
* @throws \Exception
*/
public function process(Order $order)
{
if (null !== $order->getAddresses()) {
/** @var \Magento\Sales\Model\Order\Address $address */
foreach ($order->getAddresses() as $address) {
$address->setParentId($order->getId());
$address->setOrder($order);
$address->save();
}
$billingAddress = $order->getBillingAddress();
$attributesForSave = [];
if ($billingAddress && $order->getBillingAddressId() != $billingAddress->getId()) {
$order->setBillingAddressId($billingAddress->getId());
$attributesForSave[] = 'billing_address_id';
}
$shippingAddress = $order->getShippingAddress();
if ($shippingAddress && $order->getShippigAddressId() != $shippingAddress->getId()) {
$order->setShippingAddressId($shippingAddress->getId());
$attributesForSave[] = 'shipping_address_id';
}
if (!empty($attributesForSave)) {
$this->attribute->saveAttribute($order, $attributesForSave);
}
}
return $this;
}
}