function SwitchUserListHelper::getUsers

Provides the list of accounts that can be used for the user switch.

Inactive users are omitted from all of the following db selects. Users with 'switch users' permission and anonymous user if include_anon property is set to TRUE, are prioritized.

Parameters

int $limit: The number of accounts to use for the list.

bool $include_anonymous: Whether or not to include the anonymous user.

Return value

\Drupal\Core\Session\AccountInterface[] List of accounts to be used for the switch.

File

src/SwitchUserListHelper.php, line 84

Class

SwitchUserListHelper
Switch user helper service.

Namespace

Drupal\devel

Code

public function getUsers(int $limit = 50, bool $include_anonymous = FALSE) {
    $limit = $include_anonymous ? $limit - 1 : $limit;
    // Users with 'switch users' permission are prioritized so get these first.
    $query = $this->userStorage
        ->getQuery()
        ->condition('uid', 0, '>')
        ->condition('status', 0, '>')
        ->sort('access', 'DESC')
        ->accessCheck(FALSE)
        ->range(0, $limit);
    
    /** @var array<string, RoleInterface> $roles */
    $roles = $this->roleStorage
        ->loadMultiple();
    unset($roles[AccountInterface::ANONYMOUS_ROLE]);
    $roles = array_filter($roles, static fn($role): bool => $role->hasPermission('switch users'));
    if ($roles !== [] && !isset($roles[RoleInterface::AUTHENTICATED_ID])) {
        $query->condition('roles', array_keys($roles), 'IN');
    }
    $user_ids = $query->execute();
    // If we don't have enough users with 'switch users' permission, add more
    // users until we hit $limit.
    if (count($user_ids) < $limit) {
        $query = $this->userStorage
            ->getQuery()
            ->condition('uid', 0, '>')
            ->condition('status', 0, '>')
            ->sort('access', 'DESC')
            ->accessCheck(FALSE)
            ->range(0, $limit);
        // Exclude the prioritized user ids if the previous query returned some.
        if (!empty($user_ids)) {
            $query->condition('uid', array_keys($user_ids), 'NOT IN');
            $query->range(0, $limit - count($user_ids));
        }
        $user_ids += $query->execute();
    }
    
    /** @var \Drupal\Core\Session\AccountInterface[] $accounts */
    $accounts = $this->userStorage
        ->loadMultiple($user_ids);
    if ($include_anonymous) {
        $anonymous = new AnonymousUserSession();
        $accounts[$anonymous->id()] = $anonymous;
    }
    // Syntax comes from https://php.watch/versions/8.2/partially-supported-callable-deprecation.
    uasort($accounts, self::class . '::sortUserList');
    return $accounts;
}