comparison core/lib/Drupal/Core/Session/AccountSwitcher.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\Core\Session;
4
5 /**
6 * An implementation of AccountSwitcherInterface.
7 *
8 * This allows for safe switching of user accounts by ensuring that session
9 * data for one user is not leaked in to others. It also provides a stack that
10 * allows reverting to a previous user after switching.
11 */
12 class AccountSwitcher implements AccountSwitcherInterface {
13
14 /**
15 * A stack of previous overridden accounts.
16 *
17 * @var \Drupal\Core\Session\AccountInterface[]
18 */
19 protected $accountStack = [];
20
21 /**
22 * The current user service.
23 *
24 * @var \Drupal\Core\Session\AccountProxyInterface
25 */
26 protected $currentUser = [];
27
28 /**
29 * The write-safe session handler.
30 *
31 * @var \Drupal\Core\Session\WriteSafeSessionHandlerInterface
32 */
33 protected $writeSafeHandler;
34
35 /**
36 * The original state of session saving prior to account switching.
37 *
38 * @var bool
39 */
40 protected $originalSessionSaving;
41
42 /**
43 * Constructs a new AccountSwitcher.
44 *
45 * @param \Drupal\Core\Session\AccountProxyInterface $current_user
46 * The current user service.
47 * @param \Drupal\Core\Session\WriteSafeSessionHandlerInterface $write_safe_handler
48 * The write-safe session handler.
49 */
50 public function __construct(AccountProxyInterface $current_user, WriteSafeSessionHandlerInterface $write_safe_handler) {
51 $this->currentUser = $current_user;
52 $this->writeSafeHandler = $write_safe_handler;
53 }
54
55 /**
56 * {@inheritdoc}
57 */
58 public function switchTo(AccountInterface $account) {
59 // Prevent session information from being saved and push previous account.
60 if (!isset($this->originalSessionSaving)) {
61 // Ensure that only the first session saving status is saved.
62 $this->originalSessionSaving = $this->writeSafeHandler->isSessionWritable();
63 }
64 $this->writeSafeHandler->setSessionWritable(FALSE);
65 array_push($this->accountStack, $this->currentUser->getAccount());
66 $this->currentUser->setAccount($account);
67 return $this;
68 }
69
70 /**
71 * {@inheritdoc}
72 */
73 public function switchBack() {
74 // Restore the previous account from the stack.
75 if (!empty($this->accountStack)) {
76 $this->currentUser->setAccount(array_pop($this->accountStack));
77 }
78 else {
79 throw new \RuntimeException('No more accounts to revert to.');
80 }
81 // Restore original session saving status if all account switches are
82 // reverted.
83 if (empty($this->accountStack)) {
84 if ($this->originalSessionSaving) {
85 $this->writeSafeHandler->setSessionWritable(TRUE);
86 }
87 }
88 return $this;
89 }
90
91 }