diff --git a/email_registration.module b/email_registration.module index 71095c2..e9992d8 100644 --- a/email_registration.module +++ b/email_registration.module @@ -54,6 +54,59 @@ function email_registration_user_insert(UserInterface $account) { } /** + * Implements hook_ENTITY_TYPE_presave(). + */ +function email_registration_user_presave(UserInterface $account) { + // Don't do anything for a new account: hook_ENTITY_TYPE_insert() handles + // this. + if (!$account->id()) { + return; + } + + // Don't do anything if the account email hasn't changed. + if ($account->getEmail() == $account->original->getEmail()) { + return; + } + + // Don't do anything if the account name is set to the randomly generated + // string that we set on account creation. + $name = $account->getAccountName(); + if (!empty($name) && strpos($name, 'email_registration_') === 0) { + return; + } + + // Other modules may implement hook_email_registration_name($edit, $account) + // to generate a username (return a string to be used as the username, NULL + // to have email_registration generate it). + $names = Drupal::moduleHandler()->invokeAll('email_registration_name', [$account]); + // Remove any empty entries. + $names = array_filter($names); + + if (empty($names)) { + // Strip off everything after the @ sign. + $new_name = preg_replace('/@.*$/', '', $account->getEmail()); + // Clean up the username. + $new_name = email_registration_cleanup_username($new_name); + } + else { + // One would expect a single implementation of the hook, but if there + // are multiples out there use the last one. + $new_name = array_pop($names); + } + + // Ensure whatever name we have is unique. + $new_name = email_registration_unique_username($new_name, $account->id()); + + $account->setUsername($new_name); + if ($account->isValidationRequired() && !$account->validate()) { + \Drupal::logger('email_registration')->error('Email registration failed setting the new name on user @id.', ['@id' => $account->id()]); + + // Restore the old user name. + $account->setUsername($account->original->getAccountName()); + } +} + +/** * Makes the username unique. * * Given a starting point for a Drupal username (e.g. the name portion of an