class AccountSwitcher implements AccountSwitcherInterface (View source)

An implementation of AccountSwitcherInterface.

This allows for safe switching of user accounts by ensuring that session data for one user is not leaked in to others. It also provides a stack that allows reverting to a previous user after switching.

Properties

protected AccountInterface[] $accountStack

A stack of previous overridden accounts.

protected AccountProxyInterface $currentUser

The current user service.

protected WriteSafeSessionHandlerInterface $writeSafeHandler

The write-safe session handler.

protected bool $originalSessionSaving

The original state of session saving prior to account switching.

Methods

__construct(AccountProxyInterface $current_user, WriteSafeSessionHandlerInterface $write_safe_handler)

Constructs a new AccountSwitcher.

$this
switchTo(AccountInterface $account)

Safely switches to another account.

$this
switchBack()

Reverts to a previous account after switching.

Details

__construct(AccountProxyInterface $current_user, WriteSafeSessionHandlerInterface $write_safe_handler)

Constructs a new AccountSwitcher.

Parameters

AccountProxyInterface $current_user

The current user service.

WriteSafeSessionHandlerInterface $write_safe_handler

The write-safe session handler.

$this switchTo(AccountInterface $account)

Safely switches to another account.

Each invocation of AccountSwitcherInterface::switchTo() must be matched by a corresponding invocation of AccountSwitcherInterface::switchBack() in the same function.

Parameters

AccountInterface $account

The account to switch to.

Return Value

$this $this.

$this switchBack()

Reverts to a previous account after switching.

Return Value

$this $this.

Exceptions

RuntimeException