View source
<?php
namespace Drupal\userswitch;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\SessionManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\Session\Session;
class UserSwitch {
use StringTranslationTrait;
protected $currentUser;
protected $entityTypeManager;
protected $moduleHandler;
protected $sessionManager;
protected $session;
public function __construct(AccountInterface $current_user, ModuleHandlerInterface $module_handler, SessionManagerInterface $session_manager, EntityTypeManagerInterface $entityTypeManager, Session $session) {
$this->moduleHandler = $module_handler;
$this->currentUser = $current_user;
$this->sessionManager = $session_manager;
$this->entityTypeManager = $entityTypeManager;
$this->session = $session;
}
public function isSwitchUser() {
return !empty($_SESSION['SwitchCurrentUser']);
}
public function getUserId() {
if (isset($_SESSION['SwitchCurrentUser'])) {
return $_SESSION['SwitchCurrentUser'];
}
else {
return FALSE;
}
}
public function switchToOther($target_account) {
$account = $this->currentUser
->getAccount();
$this->moduleHandler
->invokeAll('user_logout', [
$account,
]);
$this->sessionManager
->regenerate();
$_SESSION['SwitchCurrentUser'] = $account
->id();
$t_account = $this->entityTypeManager
->getStorage('user')
->load($target_account);
$this->currentUser
->setAccount($t_account);
$this->session
->set('uid', $t_account
->id());
$this->moduleHandler
->invokeAll('user_login', [
$t_account,
]);
return TRUE;
}
public function switchUserBack() {
if (empty($_SESSION['SwitchCurrentUser'])) {
return FALSE;
}
$new_user = $this->entityTypeManager
->getStorage('user')
->load($_SESSION['SwitchCurrentUser']);
unset($_SESSION['SwitchCurrentUser']);
if (!$new_user) {
return FALSE;
}
$account = $this->currentUser
->getAccount();
$this->moduleHandler
->invokeAll('user_logout', [
$account,
]);
$this->sessionManager
->regenerate();
$this->currentUser
->setAccount($new_user);
$this->session
->set('uid', $new_user
->id());
$this->moduleHandler
->invokeAll('user_login', [
$new_user,
]);
return TRUE;
}
}