You are here

public function RedhenContact::upsert in RedHen CRM 7

Saves a new contact unless a matching contact is found to update.

Updates are performed if a single contact is found matching the email address and bundle of the one being saved.

File

modules/redhen_contact/lib/redhen_contact.entity.inc, line 258
Redhen Contact entity classses.

Class

RedhenContact
The class used for contact entities.

Code

public function upsert() {
  if (isset($this->is_new) && $this->is_new && !isset($this->created)) {
    $this->updated = REQUEST_TIME;
    $contact_wrapper = entity_metadata_wrapper('redhen_contact', $this);
    $query = new EntityFieldQuery();
    $query
      ->entityCondition('entity_type', 'redhen_contact')
      ->entityCondition('bundle', $contact_wrapper
      ->getBundle())
      ->fieldCondition('redhen_contact_email', 'value', $contact_wrapper->email
      ->value(), '=');
    $result = $query
      ->execute();
    if (isset($result['redhen_contact']) && count($result['redhen_contact']) === 1) {
      list($contact_id) = array_keys($result['redhen_contact']);
      $existing_wrapper = entity_metadata_wrapper('redhen_contact', $contact_id);
      foreach ($existing_wrapper
        ->getPropertyInfo() as $property => $info) {
        if (isset($info['setter callback']) && $existing_wrapper->{$property}
          ->value() !== NULL && $contact_wrapper->{$property}
          ->value() === NULL) {

          // @todo consider a flag to avoid overriding with new values.
          $contact_wrapper->{$property}
            ->set($existing_wrapper->{$property}
            ->value());
        }
      }

      // We aren't creating a new contact, we are updating an old one, so:
      $this->contact_id = $existing_wrapper
        ->getIdentifier();
      unset($this->is_new);
      $this->is_new_revision = TRUE;
      $this->default_revision = TRUE;
    }
  }
  return $this
    ->save();
}