AddressUpdate.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Sales\Model\Order\Invoice\Plugin;
  7. class AddressUpdate
  8. {
  9. /**
  10. * @var \Magento\Sales\Model\ResourceModel\GridPool
  11. */
  12. private $gridPool;
  13. /**
  14. * @var \Magento\Sales\Model\ResourceModel\Attribute
  15. */
  16. private $attribute;
  17. /**
  18. * AddressUpdate constructor.
  19. * @param \Magento\Sales\Model\ResourceModel\GridPool $gridPool
  20. * @param \Magento\Sales\Model\ResourceModel\Attribute $attribute
  21. */
  22. public function __construct(
  23. \Magento\Sales\Model\ResourceModel\GridPool $gridPool,
  24. \Magento\Sales\Model\ResourceModel\Attribute $attribute
  25. ) {
  26. $this->gridPool = $gridPool;
  27. $this->attribute = $attribute;
  28. }
  29. /**
  30. * @param \Magento\Sales\Model\ResourceModel\Order\Handler\Address $subject
  31. * @param \Magento\Sales\Model\ResourceModel\Order\Handler\Address $result
  32. * @param \Magento\Sales\Model\Order $order
  33. * @return void
  34. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  35. */
  36. public function afterProcess(
  37. \Magento\Sales\Model\ResourceModel\Order\Handler\Address $subject,
  38. \Magento\Sales\Model\ResourceModel\Order\Handler\Address $result,
  39. \Magento\Sales\Model\Order $order
  40. ) {
  41. if ($order->hasInvoices()) {
  42. $billingAddress = $order->getBillingAddress();
  43. $shippingAddress = $order->getShippingAddress();
  44. $orderInvoiceHasChanges = false;
  45. /** @var \Magento\Sales\Model\Order\Invoice $invoice */
  46. foreach ($order->getInvoiceCollection()->getItems() as $invoice) {
  47. $invoiceAttributesForSave = [];
  48. if (!$invoice->getBillingAddressId() && $billingAddress) {
  49. $invoice->setBillingAddressId($billingAddress->getId());
  50. $invoiceAttributesForSave[] = 'billing_address_id';
  51. $orderInvoiceHasChanges = true;
  52. }
  53. if (!$invoice->getShippingAddressId() && $shippingAddress) {
  54. $invoice->setShippingAddressId($shippingAddress->getId());
  55. $invoiceAttributesForSave[] = 'shipping_address_id';
  56. $orderInvoiceHasChanges = true;
  57. }
  58. if (!empty($invoiceAttributesForSave)) {
  59. $this->attribute->saveAttribute($invoice, $invoiceAttributesForSave);
  60. }
  61. }
  62. if ($orderInvoiceHasChanges) {
  63. $this->gridPool->refreshByOrderId($order->getId());
  64. }
  65. }
  66. }
  67. }