You are here

class RedhenContactEntityController in RedHen CRM 7

The controller class for contacts.

Contains methods for the contact CRUD operations. The load method is inherited from the default controller.

Hierarchy

Expanded class hierarchy of RedhenContactEntityController

1 string reference to 'RedhenContactEntityController'
redhen_contact_entity_info in modules/redhen_contact/redhen_contact.module
Implements hook_entity_info().

File

modules/redhen_contact/lib/redhen_contact.controller.inc, line 13
The controller for the contact entity containing the CRUD operations.

View source
class RedhenContactEntityController extends EntityAPIController {

  /**
   * Saves a contact.
   *
   * @param RedhenContact $contact
   *   The full contact object to save.
   *
   * @return RedhenContact
   *   The saved contact object.
   */
  public function save($contact, DatabaseTransaction $transaction = NULL) {
    $transaction = isset($transaction) ? $transaction : db_transaction();
    try {
      $contact->updated = REQUEST_TIME;

      // New contact, set created prop.
      if (isset($contact->is_new) && $contact->is_new && !isset($contact->created)) {
        $contact->created = REQUEST_TIME;
      }
      else {
        if (!isset($contact->is_new_revision)) {
          $contact->is_new_revision = TRUE;
        }
        if (!isset($contact->default_revision)) {
          $contact->default_revision = TRUE;
        }
      }
      parent::save($contact, $transaction);

      // Set the contact user.
      if ($contact->uid) {
        $this
          ->setUser($contact, $transaction);
      }
      return $contact;
    } catch (Exception $e) {
      $transaction
        ->rollback();
      watchdog_exception($this->entityType, $e);
      throw $e;
    }
  }

  /**
   * Deletes multiple contacts by ID.
   *
   * @param array $contact_ids
   *   An array of contact IDs to delete.
   *
   * @return bool
   *   TRUE on success, FALSE otherwise.
   */
  public function delete($contact_ids, DatabaseTransaction $transaction = NULL) {
    if (!empty($contact_ids)) {
      $contacts = $this
        ->load($contact_ids, array());

      // Ensure the contacts can actually be deleted.
      foreach ((array) $contacts as $contact_id => $contact) {
        if (in_array(FALSE, module_invoke_all('redhen_contact_can_delete', $contact))) {
          unset($contacts[$contact_id]);
        }
        else {
          module_invoke_all('redhen_entity_predelete', $contact, 'redhen_contact');
        }
      }

      // If none of the specified contacts can be deleted, return FALSE.
      if (empty($contacts)) {
        return FALSE;
      }
      else {
        $contact_ids = array_keys($contacts);
      }
      $transaction = db_transaction();
      try {
        parent::delete($contact_ids, $transaction);

        // Delete user connections.
        db_delete('redhen_contact_user')
          ->condition('contact_id', $contact_ids, 'IN')
          ->execute();
      } catch (Exception $e) {
        if (isset($transaction)) {
          $transaction
            ->rollback();
        }
        watchdog_exception($this->entityType, $e);
        throw $e;
      }
    }
    return TRUE;
  }

  /**
   * Override buildQuery to add a join for the active Drupal user.
   */
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
    $query = parent::buildQuery($ids, $conditions, $revision_id);
    $query
      ->leftJoin('redhen_contact_user', 'rcu', 'rcu.contact_id = base.contact_id AND rcu.status = :status', array(
      ':status' => 1,
    ));

    // If uid is a condition, ensure the join is against the right table.
    if (isset($conditions['uid'])) {
      $query_conditions =& $query
        ->conditions();
      foreach ($query_conditions as $key => $condition) {
        if (isset($condition['field']) && $condition['field'] == 'base.uid') {
          $query_conditions[$key]['field'] = 'rcu.uid';
        }
      }
    }
    $query
      ->fields('rcu', array(
      'uid',
    ));
    return $query;
  }

  /**
   * Set the active user for a contact.
   *
   * @param RedhenContact $contact
   *   Contact object to associate.
   *
   * @return bool
   *   TRUE if contact is successfully linked to user.
   */
  public function setUser(RedhenContact $contact, DatabaseTransaction $transaction = NULL) {
    $user_result = db_select('redhen_contact_user', 'cu')
      ->fields('cu')
      ->condition('uid', $contact->uid, '=')
      ->execute();
    if ($user_result
      ->rowCount() > 0) {
      $rows = $user_result
        ->fetchAllAssoc('uid');
      foreach ($rows as $row) {

        // This user is already actively linked to this contact.
        if ($row->contact_id == $contact->contact_id && $row->status == 1) {
          return TRUE;
        }
        else {
          if ($row->contact_id != $contact->contact_id && $row->status == 1) {
            return FALSE;
          }
          else {
            if ($row->contact_id == $contact->contact_id && $row->status == NULL) {
              return FALSE;
            }
          }
        }
      }
    }

    // Now grab any record for this contact.
    $contact_result = db_select('redhen_contact_user', 'cu')
      ->fields('cu')
      ->condition('contact_id', $contact->contact_id, '=')
      ->condition('status', 1, '=')
      ->execute();
    try {

      // Contact does not have a user link, insert.
      if ($contact_result
        ->rowCount() == 0) {
        db_insert('redhen_contact_user')
          ->fields(array(
          'contact_id' => $contact->contact_id,
          'uid' => $contact->uid,
          'status' => 1,
          'created' => REQUEST_TIME,
          'updated' => REQUEST_TIME,
        ))
          ->execute();
        module_invoke_all('redhen_contact_user_update', 'insert', $contact);
      }
      else {

        // Update with new user.
        db_update('redhen_contact_user')
          ->fields(array(
          'uid' => $contact->uid,
          'updated' => REQUEST_TIME,
        ))
          ->condition('contact_id', $contact->contact_id)
          ->condition('status', 1)
          ->execute();

        // Clone the contact to populate with the old user info.
        $old_contact = clone $contact;
        $old_user = $contact_result
          ->fetchAssoc();
        $old_contact->uid = $old_user['uid'];
        module_invoke_all('redhen_contact_user_update', 'update', $contact, $old_contact);
      }
      return TRUE;
    } catch (Exception $e) {
      if (isset($transaction)) {
        $transaction
          ->rollback();
      }
      watchdog_exception($this->entityType, $e);
      throw $e;
    }
  }

  /**
   * Delete or unlink the active user for a contact.
   *
   * @param RedhenContact $contact
   *   RedHen contact object.
   * @param bool $delete
   *   If true, the connection is deleted and can be recreated. False sets the
   *   connection to inactive which will prevent it from being reconnected on
   *   subsequent attempts.
   *
   * @return bool
   *   TRUE if user is successfully deleted or unlinked from contact.
   */
  public function deleteUser(RedhenContact $contact, $delete = FALSE, DatabaseTransaction $transaction = NULL) {
    try {
      $wrapper = entity_metadata_wrapper('redhen_contact', $contact);
      $user = $wrapper->user
        ->value();
      if ($delete) {
        db_delete('redhen_contact_user')
          ->condition('contact_id', $contact->contact_id)
          ->condition('uid', $user->uid)
          ->execute();
      }
      else {
        db_update('redhen_contact_user')
          ->condition('contact_id', $contact->contact_id)
          ->condition('uid', $user->uid)
          ->fields(array(
          'status' => NULL,
        ))
          ->execute();
      }
      module_invoke_all('redhen_contact_user_update', 'delete', $contact);
      unset($contact->uid);
      return TRUE;
    } catch (Exception $e) {
      if (isset($transaction)) {
        $transaction
          ->rollback();
      }
      watchdog_exception($this->entityType, $e);
      throw $e;
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DrupalDefaultEntityController::$cache protected property Whether this entity type should use the static cache.
DrupalDefaultEntityController::$entityCache protected property Static cache of entities, keyed by entity ID.
DrupalDefaultEntityController::$entityInfo protected property Array of information about the entity.
DrupalDefaultEntityController::$entityType protected property Entity type for this controller instance.
DrupalDefaultEntityController::$hookLoadArguments protected property Additional arguments to pass to hook_TYPE_load().
DrupalDefaultEntityController::$idKey protected property Name of the entity's ID field in the entity database table.
DrupalDefaultEntityController::$revisionKey protected property Name of entity's revision database table field, if it supports revisions.
DrupalDefaultEntityController::$revisionTable protected property The table that stores revisions, if the entity supports revisions.
DrupalDefaultEntityController::attachLoad protected function Attaches data to entities upon loading. 4
DrupalDefaultEntityController::cacheGet protected function Gets entities from the static cache. 1
DrupalDefaultEntityController::cacheSet protected function Stores entities in the static entity cache.
DrupalDefaultEntityController::cleanIds protected function Ensures integer entity IDs are valid.
DrupalDefaultEntityController::filterId protected function Callback for array_filter that removes non-integer IDs.
EntityAPIController::$bundleKey protected property
EntityAPIController::$cacheComplete protected property
EntityAPIController::$defaultRevisionKey protected property
EntityAPIController::buildContent public function Implements EntityAPIControllerInterface. Overrides EntityAPIControllerInterface::buildContent
EntityAPIController::create public function Implements EntityAPIControllerInterface. Overrides EntityAPIControllerInterface::create
EntityAPIController::deleteRevision public function Implements EntityAPIControllerRevisionableInterface::deleteRevision(). Overrides EntityAPIControllerRevisionableInterface::deleteRevision
EntityAPIController::export public function Implements EntityAPIControllerInterface. Overrides EntityAPIControllerInterface::export 1
EntityAPIController::import public function Implements EntityAPIControllerInterface. Overrides EntityAPIControllerInterface::import
EntityAPIController::invoke public function Implements EntityAPIControllerInterface. Overrides EntityAPIControllerInterface::invoke 1
EntityAPIController::load public function Overridden. Overrides DrupalDefaultEntityController::load 1
EntityAPIController::query public function Builds and executes the query for loading.
EntityAPIController::renderEntityProperty protected function Renders a single entity property.
EntityAPIController::resetCache public function Overrides DrupalDefaultEntityController::resetCache(). Overrides DrupalDefaultEntityController::resetCache 1
EntityAPIController::saveRevision protected function Saves an entity revision.
EntityAPIController::view public function Implements EntityAPIControllerInterface. Overrides EntityAPIControllerInterface::view 1
EntityAPIController::__construct public function Overridden. Overrides DrupalDefaultEntityController::__construct 1
RedhenContactEntityController::buildQuery protected function Override buildQuery to add a join for the active Drupal user. Overrides EntityAPIController::buildQuery
RedhenContactEntityController::delete public function Deletes multiple contacts by ID. Overrides EntityAPIController::delete
RedhenContactEntityController::deleteUser public function Delete or unlink the active user for a contact.
RedhenContactEntityController::save public function Saves a contact. Overrides EntityAPIController::save
RedhenContactEntityController::setUser public function Set the active user for a contact.