You are here

function regcode_code_consume in Registration codes 8

Same name and namespace in other branches
  1. 7.2 regcode.module \regcode_code_consume()
  2. 7 regcode.module \regcode_code_consume()

Consumes a regcode and attribute it to a user.

Parameters

string $regcode: The registration code.

int $account_id: Optional user id to assign the given code to.

Return value

mixed An error code, or TRUE if the code was assigned successfully.

1 call to regcode_code_consume()
regcode_user_register_form_submit_handler in ./regcode.module
Updates data for a regcode in the database.

File

./regcode.module, line 249
Main functionality and hooks of regcode module.

Code

function regcode_code_consume($regcode, $account_id) {
  $code = regcode_code_validate($regcode);

  // Check the code validated, otherwise return the error code.
  if (!is_object($code)) {
    return $code;
  }
  $code->uses++;

  // Mark the code inactive if it's used up.
  $active = 1;
  if ($code->maxuses != 0 && $code->uses >= $code->maxuses) {
    $active = 0;
  }

  // Use the code.
  \Drupal::database()
    ->update('regcode')
    ->fields([
    'uses' => $code->uses,
    'lastused' => \Drupal::time()
      ->getRequestTime(),
    'uid' => $account_id,
    'is_active' => $active,
  ])
    ->condition('rid', $code->rid)
    ->execute();

  // Trigger the regcode_used hook.
  $account = \Drupal::service('entity_type.manager')
    ->getStorage('user')
    ->load($account_id);
  $account->regcode = $code;
  foreach (\Drupal::moduleHandler()
    ->getImplementations('regcode_used') as $module) {
    $hook = $module . '_regcode_used';
    $hook($code, $account);
  }
  return $code;
}