You are here

public function NodeRegistrationController::save in Node registration 7

Override save() to add automatic base column values from other base column values.

Overrides EntityAPIController::save

File

includes/node_registration.entity.inc, line 149
Entity hooks and callbacks for registrations.

Class

NodeRegistrationController
Controller class Node Registrations

Code

public function save($registration) {

  // Add `type` and `node_type` from `node` or `nid`.
  if (empty($registration->type) || empty($registration->node_type)) {
    $node = NULL;
    if (!empty($registration->node)) {
      $node = $registration->node;
      $registration->nid = $node->nid;
    }
    elseif (!empty($registration->nid)) {
      $node = node_load($registration->nid);
      $registration->node = $node;
    }
    if ($node) {
      if (empty($registration->type)) {
        $registration->type = !empty($node->registration->private_fields) ? 'node_' . $node->nid : $node->type;
      }
      if (empty($registration->node_type)) {
        $registration->node_type = $node->type;
      }
    }
  }

  // Add `weight`.
  if ((!isset($registration->weight) || $registration->weight === '') && !empty($registration->nid)) {
    $weight = db_query('SELECT MAX(weight) FROM {node_registration} WHERE nid = ?', array(
      $registration->nid,
    ))
      ->fetchField();
    $registration->weight = $weight === NULL ? 0 : $weight + 1;
  }

  // Add `author_uid` from session user.
  if (!isset($registration->author_uid)) {
    global $user;
    $registration->author_uid = $user->uid;
  }

  // Add `uid` from `user_name`.
  if (!isset($registration->uid) && !empty($registration->user_name)) {
    static $user_name_uid_map = array();
    $name = trim(drupal_strtolower($registration->user_name));
    if (!isset($user_name_uid_map[$name])) {
      $user_name_uid_map[$name] = db_query('SELECT uid FROM {users} WHERE name = ?', array(
        $name,
      ))
        ->fetchField() ?: 0;
    }
    $registration->uid = $user_name_uid_map[$name];
  }

  // Add `uid` from `user_mail`.
  if (!isset($registration->uid) && !empty($registration->user_mail)) {
    static $user_mail_uid_map = array();
    $mail = trim(drupal_strtolower($registration->user_mail));
    if (!isset($user_mail_uid_map[$mail])) {
      $user_mail_uid_map[$mail] = db_query('SELECT uid FROM {users} WHERE mail = ?', array(
        $mail,
      ))
        ->fetchField() ?: 0;
    }
    $registration->uid = $user_mail_uid_map[$mail];
  }

  // Add `email` from `uid`.
  if (empty($registration->email) && !empty($registration->uid)) {
    static $uid_email_map = array();
    $uid = (int) trim($registration->uid);
    if (!isset($uid_email_map[$uid])) {
      $uid_email_map[$uid] = db_query('SELECT mail FROM {users} WHERE uid = ?', array(
        $uid,
      ))
        ->fetchField() ?: 0;
    }
    $registration->email = $uid_email_map[$uid];
  }
  return parent::save($registration);
}