You are here

registration_role.module in Registration role 8

Module file for Registration role.

File

registration_role.module
View source
<?php

/**
 * @file
 * Module file for Registration role.
 */
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\user\UserInterface;

/**
 * Implements hook_help().
 */
function registration_role_help($route_name, RouteMatchInterface $route_match) {
  $output = '';
  switch ($route_name) {
    case 'help.page.registration_role':
      $output = t("Auto-assign a role upon registration.");
      return $output;
  }
}

/**
 * Implements hook_ENTITY_TYPE_presave() for user entities.
 */
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);
    }
  }
}

Functions

Namesort descending Description
registration_role_help Implements hook_help().
registration_role_user_presave Implements hook_ENTITY_TYPE_presave() for user entities.