You are here

public function AddressBook::copy in Commerce Core 8.2

Copies the profile to the customer's address book.

If the customer is allowed to have multiple profiles of this type, the given profile will be duplicated and assigned to them. If the given profile was already copied to the customer's address book once, the matching address book profile will be updated instead.

If the customer is only allowed to have a single profile of this type, the default profile will be loaded (created if missing) and updated.

Parameters

\Drupal\profile\Entity\ProfileInterface $profile: The profile.

\Drupal\user\UserInterface $customer: The customer.

Overrides AddressBookInterface::copy

File

modules/order/src/AddressBook.php, line 133

Class

AddressBook

Namespace

Drupal\commerce_order

Code

public function copy(ProfileInterface $profile, UserInterface $customer) {
  if ($customer
    ->isAnonymous()) {
    return;
  }

  // Check if there is an existing address book profile to update.
  // This can happen in two scenarios:
  // 1) The profile was already copied to the address book once.
  // 2) The customer is only allowed to have a single address book profile.
  $address_book_profile = NULL;
  $address_book_profile_id = $profile
    ->getData('address_book_profile_id');
  if ($address_book_profile_id) {

    /** @var \Drupal\profile\Entity\ProfileInterface $address_book_profile */
    $address_book_profile = $this->profileStorage
      ->load($address_book_profile_id);
  }
  if (!$address_book_profile && !$this
    ->allowsMultiple($profile
    ->bundle())) {
    $address_book_profile = $this
      ->load($customer, $profile
      ->bundle());
  }
  if ($address_book_profile) {
    $address_book_profile
      ->populateFromProfile($profile);
    $address_book_profile
      ->save();
  }
  else {
    $address_book_profile = $profile
      ->createDuplicate();
    $address_book_profile
      ->setOwnerId($customer
      ->id());
    $address_book_profile
      ->unsetData('copy_to_address_book');
    $address_book_profile
      ->save();
  }
  $profile
    ->unsetData('copy_to_address_book');
  $profile
    ->setData('address_book_profile_id', $address_book_profile
    ->id());
  $profile
    ->save();
}