class BulkAddCasUsers in CAS 8
Same name and namespace in other branches
- 2.x src/Form/BulkAddCasUsers.php \Drupal\cas\Form\BulkAddCasUsers
Class BulkAddCasUsers.
A form for bulk registering CAS users.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\cas\Form\BulkAddCasUsers
Expanded class hierarchy of BulkAddCasUsers
1 string reference to 'BulkAddCasUsers'
File
- src/
Form/ BulkAddCasUsers.php, line 19
Namespace
Drupal\cas\FormView source
class BulkAddCasUsers extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'bulk_add_cas_users';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['intro'] = [
'#prefix' => '<p>',
'#markup' => $this
->t('Use this form to pre-register one or more users, allowing them to log in using CAS.'),
'#suffix' => '</p>',
];
$form['cas_usernames'] = [
'#type' => 'textarea',
'#title' => $this
->t('CAS username(s)'),
'#required' => TRUE,
'#default_value' => '',
'#description' => $this
->t('Enter one username per line.'),
];
$form['email_hostname'] = [
'#type' => 'textfield',
'#title' => $this
->t('Email address'),
'#description' => $this
->t("The email domain name used to combine with the username to form the user's email address. If your user's email address is usually provided via a CAS attribute, that will not work here because CAS attributes are not available."),
'#field_prefix' => $this
->t('username@'),
'#required' => TRUE,
'#default_value' => $this
->config('cas.settings')
->get('user_accounts.email_hostname'),
];
$roles = array_map([
'\\Drupal\\Component\\Utility\\Html',
'escape',
], user_role_names(TRUE));
$form['roles'] = [
'#type' => 'checkboxes',
'#title' => $this
->t('Role(s)'),
'#options' => $roles,
'#description' => $this
->t('Optionally assign one or more roles to each user. Note that if you have CAS configured to assign roles during automatic registration on login, those will be ignored.'),
];
$form['roles'][RoleInterface::AUTHENTICATED_ID] = [
'#default_value' => TRUE,
'#disabled' => TRUE,
];
$form['extra_info'] = [
'#prefix' => '<p>',
'#markup' => $this
->t("Note that because CAS attributes are only available when a user authenticates with CAS, any role or field assignment based on attributes will not be available."),
'#suffix' => '</p>',
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Create new accounts'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$roles = array_filter($form_state
->getValue('roles'));
unset($roles[RoleInterface::AUTHENTICATED_ID]);
$roles = array_keys($roles);
$cas_usernames = trim($form_state
->getValue('cas_usernames'));
$cas_usernames = preg_split('/[\\n\\r|\\r|\\n]+/', $cas_usernames);
$email_hostname = trim($form_state
->getValue('email_hostname'));
$operations = [];
foreach ($cas_usernames as $cas_username) {
$cas_username = trim($cas_username);
if (!empty($cas_username)) {
$operations[] = [
'\\Drupal\\cas\\Form\\BulkAddCasUsers::userAdd',
[
$cas_username,
$roles,
$email_hostname,
],
];
}
}
$batch = [
'title' => $this
->t('Creating CAS users...'),
'operations' => $operations,
'finished' => '\\Drupal\\cas\\Form\\BulkAddCasUsers::userAddFinished',
'progress_message' => $this
->t('Processed @current out of @total.'),
];
batch_set($batch);
}
/**
* Perform a single CAS user creation batch operation.
*
* Callback for batch_set().
*
* @param string $cas_username
* The CAS username, which will also become the Drupal username.
* @param array $roles
* An array of roles to assign to the user.
* @param array $context
* The batch context array, passed by reference.
* @param string $email_hostname
* The hostname to combine with the username to create the email address.
*/
public static function userAdd($cas_username, array $roles, $email_hostname, array &$context) {
$cas_user_manager = \Drupal::service('cas.user_manager');
// Back out of an account already has this CAS username.
$existing_uid = $cas_user_manager
->getUidForCasUsername($cas_username);
if ($existing_uid) {
$context['results']['messages']['already_exists'][] = $cas_username;
return;
}
$user_properties = [
'roles' => $roles,
'mail' => $cas_username . '@' . $email_hostname,
];
try {
/** @var \Drupal\user\UserInterface $user */
$user = $cas_user_manager
->register($cas_username, $user_properties, $cas_username);
$context['results']['messages']['created'][] = $user
->toLink()
->toString();
} catch (CasLoginException $e) {
\Drupal::logger('cas')
->error('CasLoginException when registering user with name %name: %e', [
'%name' => $cas_username,
'%e' => $e
->getMessage(),
]);
$context['results']['messages']['errors'][] = $cas_username;
return;
}
}
/**
* Complete CAS user creation batch process.
*
* Callback for batch_set().
*
* Consolidates message output.
*/
public static function userAddFinished($success, $results, $operations) {
$messenger = \Drupal::messenger();
if ($success) {
if (!empty($results['messages']['errors'])) {
$messenger
->addError(t('An error was encountered creating accounts for the following users (check logs for more details): %usernames', [
'%usernames' => implode(', ', $results['messages']['errors']),
]));
}
if (!empty($results['messages']['already_exists'])) {
$messenger
->addError(t('The following accounts were not registered because existing accounts are already using the usernames: %usernames', [
'%usernames' => implode(', ', $results['messages']['already_exists']),
]));
}
if (!empty($results['messages']['created'])) {
$userLinks = Markup::create(implode(', ', $results['messages']['created']));
$messenger
->addStatus(t('Successfully created accounts for the following usernames: %usernames', [
'%usernames' => $userLinks,
]));
}
}
else {
// An error occurred.
// $operations contains the operations that remained unprocessed.
$error_operation = reset($operations);
$messenger
->addError(t('An error occurred while processing %error_operation with arguments: @arguments', [
'%error_operation' => $error_operation[0],
'@arguments' => print_r($error_operation[1], TRUE),
]));
}
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
BulkAddCasUsers:: |
public | function |
Form constructor. Overrides FormInterface:: |
|
BulkAddCasUsers:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
BulkAddCasUsers:: |
public | function |
Form submission handler. Overrides FormInterface:: |
|
BulkAddCasUsers:: |
public static | function | Perform a single CAS user creation batch operation. | |
BulkAddCasUsers:: |
public static | function | Complete CAS user creation batch process. | |
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
public static | function |
Instantiates a new instance of this class. Overrides ContainerInjectionInterface:: |
87 |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
FormBase:: |
public | function |
Form validation handler. Overrides FormInterface:: |
62 |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |