You are here

function registration_role_user_presave in Registration role 8

Implements hook_ENTITY_TYPE_presave() for user entities.

File

./registration_role.module, line 26
Module file for Registration role.

Code

function registration_role_user_presave(UserInterface $user) {
  $config = \Drupal::config('registration_role.setting');
  $case = $config
    ->get('registration_mode');

  // Do not assign the roles by default.
  $assign_roles = FALSE;

  // Get the current user id.
  $current_user_id = \Drupal::currentUser()
    ->id();
  if ($current_user_id == 0 && PHP_SAPI !== 'cli') {

    // If the current user id is 0, then this user is self registrating, so ask
    // the module to assign roles, if applicable.
    $assign_roles = TRUE;
  }
  elseif (($current_user_id != 0 || PHP_SAPI === 'cli') && $case == 'admin') {

    // If the current user id is not 0, then another user (admin, or anyone with
    // the right permission) is creating this user, so the module will be asked
    // to assign roles only if the setting is set to 'admin'.
    $assign_roles = TRUE;
  }
  if ($user
    ->isNew() && $assign_roles) {
    $config = \Drupal::config('registration_role.setting');
    foreach ($config
      ->get('role_to_select') as $key => $value) {
      $user
        ->addRole($key);
    }
  }
}