You are here

public function UcAddressesAddress::save in Ubercart Addresses 6.2

Same name and namespace in other branches
  1. 7 class/UcAddressesAddress.class.php \UcAddressesAddress::save()

Saves address if address is marked as 'dirty'.

@access public

Return value

void

Throws

UcAddressesDbException

UcAddressesUnownedException

File

class/UcAddressesAddress.class.php, line 471
Contains the UcAddressesAddress class.

Class

UcAddressesAddress
The main address class used by uc_addresses (and extension modules).

Code

public function save() {
  if (!$this
    ->isOwned()) {
    throw new UcAddressesUnownedException(t('The address can not be saved because it is not owned by an user.'));
  }
  if ($this
    ->isDirty()) {

    // Allow other modules to alter the address before saving.
    module_invoke_all('uc_addresses_address_presave', $this);
    $address = $this
      ->getSchemaAddress();
    $address->modified = time();
    $address->uid = $this
      ->getUserId();
    if ($address->aid < 0) {
      unset($address->aid);
      $address->created = time();
      $result = drupal_write_record('uc_addresses', $address);
      $hook = 'insert';

      // Tell address book the address now has a definitive ID.
      $this->addressBook
        ->updateAddress($this);
    }
    else {
      $result = drupal_write_record('uc_addresses', $address, array(
        'aid',
      ));
      $hook = 'update';
    }
    if ($result === FALSE) {
      throw new UcAddressesDbException(t('Failed to write address with id = %aid', array(
        '%aid' => $address->aid,
      )));
    }

    // Address is saved and no longer 'dirty'.
    $this
      ->clearDirty();

    // If this a default address, ensure no other addresses are marked as
    // default in the database.
    if (function_exists('uc_addresses_address_types')) {

      // During installation the function 'uc_addresses_address_types()'
      // may not be available yet.
      $default_types = uc_addresses_address_types();
    }
    else {
      $default_types = array(
        'shipping',
        'billing',
      );
    }
    foreach ($default_types as $default_type) {
      if ($this
        ->isDefault($default_type)) {

        // Mark all addresses of the address owner as non-default except
        // the current address.
        db_query("UPDATE {uc_addresses} SET default_%s = 0 WHERE uid = %d AND aid != %d", $default_type, $address->uid, $address->aid);
      }
    }

    // Notify other modules that an address has been saved.
    module_invoke_all('uc_addresses_address_' . $hook, $this);
  }
}