Change record status: 
Project: 
Introduced in branch: 
11.4.x
Introduced in version: 
11.4.0
Description: 

The user cancellation feature has been refactored:

Service to cancel user accounts

A new service, Drupal\user\AccountCancellation, was introduced to replace current procedural code related ti user account cancellation.

Cancel an account

Before

$edit = ['user_cancel_notify' => TRUE];
user_cancel($edit, 123, 'user_cancel_block');

After

use Drupal\user\AccountCancellation;
use Drupal\user\Entity\User;
...
$context = ['user_cancel_notify' => TRUE];
$account = User::load(123);
// Inject service where possible.
\Drupal::service(AccountCancellation::class)->cancel($account, 'user_cancel_block', $context);

Define custom cancellation methods

Before

function my_module_user_cancel_methods_alter(&$methods) {
  $methods['my_module_zero_out'] = [
    'title' => t('Delete the account and remove all content.'),
    'description' => t('All your content will be replaced by empty strings.'),
    // Access should be used for administrative methods only.
    'access' => $account->hasPermission('access zero-out account cancellation method'),
  ];
}

After

Create a new plugin in my_module, under src/Plugin/user/CancelMethod

#[AccountCancelMethod(
  id: 'zero_out',
  label: new TranslatableMarkup('Delete the account and remove all content.'),
  description: new TranslatableMarkup('All your content will be replaced by empty strings.'),
)]
class ZeroOut extends AccountCancelMethodPluginBase {
  public function access(AccountInterface $account): bool {
    return $account->hasPermission('access zero-out account cancellation method');
  }
  public function cancel(UserInterface $account, array $context = []): void {
    \Drupal::logger('my_module')->notice('We will miss you!');
  }
}

Get the cancellation method form element

Before

$methods = user_cancel_methods();

After

use Drupal\user\AccountCancellation;
...
// Inject service where possible.
$methods = \Drupal::service(AccountCancellation::class)->getMethodsFormElement();

Other deprecations

Procedural functions:

Function Replacement
_user_cancel() \Drupal\user\AccountCancellation::cancelAccount()
_user_cancel_session_regenerate() \Drupal\user\AccountCancellation::regenerateSession()

Constructor parameter additions

Class Service Position
Drupal\jsonapi\Controller\EntityResource Drupal\user\AccountCancellation 12
Drupal\user\Controller\UserController Drupal\user\AccountCancellation 6
Drupal\user\Form\UserCancelForm Drupal\user\AccountCancellation 3
Drupal\user\Form\UserMultipleCancelConfirm Drupal\user\AccountCancellation 3
Drupal\user\AccountSettingsForm Drupal\user\AccountCancellation 3
Drupal\user\AccountSettingsForm Drupal\user\AccountCancellation 3
Impacts: 
Module developers
Site templates, recipes and distribution developers