public function BulkUserRegistration::createUser in Bulk User Registration 8
Creates and saves a user.
Parameters
array $userData: Structured array of user data.
string $defaultRole: The machine name of the default user role.
Return value
\Drupal\user\UserInterface The saved user.
Overrides BulkUserRegistrationInterface::createUser
File
- src/
BulkUserRegistration.php, line 55
Class
- BulkUserRegistration
- The BulkUserRegistration service.
Namespace
Drupal\bulk_user_registrationCode
public function createUser(array $userData, $defaultRole) {
$langcode = \Drupal::languageManager()
->getDefaultLanguage()
->getId();
/** @var \Drupal\user\UserInterface $user */
$user = User::create();
$user
->setUsername($userData[self::FIELD_USER_NAME]);
$user
->setEmail($userData[self::FIELD_EMAIL]);
$user
->set('init', $userData[self::FIELD_EMAIL]);
$user
->set('langcode', $langcode);
$user
->set('preferred_langcode', $langcode);
$user
->set('preferred_admin_langcode', $langcode);
$user
->enforceIsNew();
if (!$userData[self::FIELD_STATUS]) {
$user
->block();
}
else {
$user
->activate();
}
// Single or multiple roles will be applied to the user object. Multiple
// roles should be comma separated.
$roles = [];
$csvRoles = explode(',', $userData[self::FIELD_ROLE]);
$allowedRoles = $this
->getAllowedRoles();
foreach ($csvRoles as $csvRole) {
$csvRole = trim($csvRole);
if (isset($allowedRoles[$csvRole])) {
$roles[] = $csvRole;
}
}
$roles = array_filter(array_unique($roles));
$roles = empty($roles) ? [
$defaultRole,
] : $roles;
foreach ($roles as $role) {
$this
->addRole($user, $role);
}
// Allow modules to modify the user object before saving it. Typically used
// to store the extra field data into the user.
\Drupal::moduleHandler()
->invokeAll('bulk_user_registration_user_presave', [
$user,
$userData,
]);
$user
->save();
return $user;
}