Address.php 2.3 KB

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