function AdminAccountSwitcher::switchToAdministrator

Same name in other branches
  1. 10 core/lib/Drupal/Core/DefaultContent/AdminAccountSwitcher.php \Drupal\Core\DefaultContent\AdminAccountSwitcher::switchToAdministrator()

Switches to an administrative account.

This will switch to the first available account with a role that has the `is_admin` flag. If there are no such roles, or no such users, this will try to switch to user 1 if superuser access is enabled.

Return value

\Drupal\Core\Session\AccountInterface The account that was switched to.

Throws

\Drupal\Core\Access\AccessException Thrown if there are no users with administrative roles.

File

core/lib/Drupal/Core/DefaultContent/AdminAccountSwitcher.php, line 37

Class

AdminAccountSwitcher
@internal This API is experimental.

Namespace

Drupal\Core\DefaultContent

Code

public function switchToAdministrator() : AccountInterface {
    $admin_roles = $this->entityTypeManager
        ->getStorage('user_role')
        ->getQuery()
        ->condition('is_admin', TRUE)
        ->execute();
    $user_storage = $this->entityTypeManager
        ->getStorage('user');
    if ($admin_roles) {
        $accounts = $user_storage->getQuery()
            ->accessCheck(FALSE)
            ->condition('roles', $admin_roles, 'IN')
            ->condition('status', 1)
            ->sort('uid')
            ->range(0, 1)
            ->execute();
    }
    else {
        $accounts = [];
    }
    $account = $user_storage->load(reset($accounts) ?: 1);
    assert($account instanceof AccountInterface);
    if (array_intersect($account->getRoles(), $admin_roles) || (int) $account->id() === 1 && $this->isSuperUserAccessEnabled) {
        $this->switchTo($account);
        return $account;
    }
    throw new AccessException("There are no user accounts with administrative roles.");
}

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