Relation.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Customer\Model\ResourceModel\Customer;
  7. /**
  8. * Class Relation
  9. */
  10. class Relation implements \Magento\Framework\Model\ResourceModel\Db\VersionControl\RelationInterface
  11. {
  12. /**
  13. * Save relations for Customer
  14. *
  15. * @param \Magento\Framework\Model\AbstractModel $customer
  16. * @return void
  17. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  18. */
  19. public function processRelation(\Magento\Framework\Model\AbstractModel $customer)
  20. {
  21. $defaultBillingId = $customer->getData('default_billing');
  22. $defaultShippingId = $customer->getData('default_shipping');
  23. if (!$customer->getData('ignore_validation_flag')) {
  24. /** @var \Magento\Customer\Model\Address $address */
  25. foreach ($customer->getAddresses() as $address) {
  26. if ($address->getData('_deleted')) {
  27. if ($address->getId() == $defaultBillingId) {
  28. $customer->setData('default_billing', null);
  29. }
  30. if ($address->getId() == $defaultShippingId) {
  31. $customer->setData('default_shipping', null);
  32. }
  33. $removedAddressId = $address->getId();
  34. $address->delete();
  35. // Remove deleted address from customer address collection
  36. $customer->getAddressesCollection()->removeItemByKey($removedAddressId);
  37. } else {
  38. $address->setParentId(
  39. $customer->getId()
  40. )->setStoreId(
  41. $customer->getStoreId()
  42. )->setIsCustomerSaveTransaction(
  43. true
  44. )->save();
  45. if (($address->getIsPrimaryBilling() ||
  46. $address->getIsDefaultBilling()) && $address->getId() != $defaultBillingId
  47. ) {
  48. $customer->setData('default_billing', $address->getId());
  49. }
  50. if (($address->getIsPrimaryShipping() ||
  51. $address->getIsDefaultShipping()) && $address->getId() != $defaultShippingId
  52. ) {
  53. $customer->setData('default_shipping', $address->getId());
  54. }
  55. }
  56. }
  57. }
  58. $changedAddresses = [];
  59. $changedAddresses['default_billing'] = $customer->getData('default_billing');
  60. $changedAddresses['default_shipping'] = $customer->getData('default_shipping');
  61. $customer->getResource()->getConnection()->update(
  62. $customer->getResource()->getTable('customer_entity'),
  63. $changedAddresses,
  64. $customer->getResource()->getConnection()->quoteInto('entity_id = ?', $customer->getId())
  65. );
  66. }
  67. }