I have a custom module saving user accounts from a customer API.
For this I use the \Drupal\user\Entity\User::create method, and I initialise the user account with the code above:
/**
* Save a Drupal user using `mail`.
*
* @param array $data
* The User data to save.
*
* @return bool|int
* Result: SAVED_NEW or FALSE.
*/
public static function saveUser(array $data) {
// Only if user exists on API
if (empty($data['mail'])) {
return FALSE;
}
// Create the user
$email = $data['mail'];
$user = \Drupal\user\Entity\User::create();
$lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
// The Basics
$user->setEmail($email);
$user->setUsername($email);
$user->set("init", $email);
$user->set("langcode", $lang);
$user->set("preferred_langcode", $lang);
$user->set("preferred_admin_langcode", $lang);
$user->enforceIsNew();
$user->setPassword(user_password());
$user->activate();
// Save user.
return $user->save();
}
I like to look for a good way of doing things and to read about getting D9 ready for my modules. When it is necessary, I also inspect the core code to see the available methods and how core modules are made to inspire me.
I found this interesting topic about Entity Validation API, where it speaks about using validation on entities. I also found that user object has methods to know if a validation is necessary and to validate, and the preSave method will throw an exception if the validation is necessary and not done.
All the examples and code snippet I found on internet about creating a user programmatically never use any kind of validation, and I wonder if this is something new or if it is just not really necessary for my case.
As I said, I save data from a remote API, and I do not manage the quality of the email address I use as email and username. I also do not verify if those values already exist.
Should I add something like this ?
// Entity validation
if ($user->isValidationRequired()) {
$violations = $user->validate();
if (count($violations)) {
\Drupal::messenger()->addError($violations[0]->getMessage());
return FALSE;
}
}