function AccountCancellation::cancel

Same name and namespace in other branches
  1. main core/modules/user/src/AccountCancellation.php \Drupal\user\AccountCancellation::cancel()

Cancel a user account.

Since the user cancellation process needs to be run in a batch, either Form API will invoke it, or batch_process() needs to be invoked after calling this function and should define the path to redirect to.

Parameters

array $edit: An array of submitted form values.

int $uid: The user ID of the user account to cancel.

string $method: The account cancellation method to use.

See also

static::cancelAccount()

File

core/modules/user/src/AccountCancellation.php, line 58

Class

AccountCancellation
User account cancellation service.

Namespace

Drupal\user

Code

public function cancel(array $edit, int $uid, string $method) : void {
  $account = $this->entityTypeManager
    ->getStorage('user')
    ->load($uid);
  if (!$account) {
    $this->messenger
      ->addError($this->t('The user account %id does not exist.', [
      '%id' => $uid,
    ]));
    $this->logger
      ->error('Attempted to cancel non-existing user account: %id.', [
      '%id' => $uid,
    ]);
    return;
  }
  // Initialize batch (to set title).
  $batchBuilder = (new BatchBuilder())->setTitle($this->t('Cancelling account'));
  batch_set($batchBuilder->toArray());
  // When the 'user_cancel_delete' method is used, user_delete() is called,
  // which invokes hook_ENTITY_TYPE_predelete() and hook_ENTITY_TYPE_delete()
  // for the user entity. Modules should use those hooks to respond to the
  // account deletion.
  if ($method != 'user_cancel_delete') {
    // Allow modules to add further sets to this batch.
    $this->moduleHandler
      ->invokeAll('user_cancel', [
      $edit,
      $account,
      $method,
    ]);
  }
  // Finish the batch and actually cancel the account.
  $batchBuilder = (new BatchBuilder())->setTitle($this->t('Cancelling user account'))
    ->addOperation(static::class . ':cancelAccount', [
    $edit,
    $account,
    $method,
  ]);
  // After cancelling account, ensure that user is logged out.
  if ($account->id() == $this->currentUser
    ->id()) {
    // Batch API stores data in the session, so use the finished operation to
    // manipulate the current user's session id.
    $batchBuilder->setFinishCallback(static::class . ':regenerateSession');
  }
  batch_set($batchBuilder->toArray());
  // Batch processing is either handled via Form API or has to be invoked
  // manually.
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.