Completed
Push — develop ( db3c5e...d25888 )
by
unknown
19:17
created

UserSwitcher::setSessionParam()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @license MIT
7
 * @copyright  2013 - 2017 Cross Solution <http://cross-solution.de>
8
 */
9
  
10
/** */
11
namespace Auth\Controller\Plugin;
12
13
use Auth\Entity\UserInterface;
14
use Zend\Authentication\AuthenticationService;
15
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
16
use Zend\Session\Container;
17
use Zend\Stdlib\ArrayUtils;
18
19
/**
20
 * Plugin to switch logged in user w/o authentication.
21
 * 
22
 * @author Mathias Gelhausen <[email protected]>
23
 * @since 0.29
24
 */
25
class UserSwitcher extends AbstractPlugin
26
{
27
    const SESSION_NAMESPACE = "SwitchedUser";
28
29
    /**
30
     * AuthenticationService
31
     *
32
     * @var \Zend\Authentication\AuthenticationService
33
     */
34
    private $auth;
35
36
    /**
37
     * The session container.
38
     *
39
     * @var Container
40
     */
41
    private $sessionContainer;
42
43
    /**
44
     * Creates an instance
45
     *
46
     * @param AuthenticationService $auth
47
     */
48
    public function __construct(AuthenticationService $auth)
49
    {
50
        $this->auth = $auth;
51
    }
52
53
    /**
54
     * Switch to or restore an user.
55
     *
56
     * If $userId is not null, attempt to switch the user,
57
     * restore the original user otherwise.
58
     *
59
     * @param null|string $userId
60
     *
61
     * @return bool
62
     */
63
    public function __invoke($userId = null, array $params = [])
0 ignored issues
show
Coding Style introduced by
function __invoke() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
64
    {
65
        if (null === $userId) {
66
            return $this->clear();
67
        }
68
69
        return $this->switchUser($userId, $params);
70
    }
71
72
    /**
73
     * Restores the original user.
74
     *
75
     * @return bool
76
     */
77
    public function clear()
0 ignored issues
show
Coding Style introduced by
function clear() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
78
    {
79
        $session = $this->getSessionContainer();
80
        if (!$session->isSwitchedUser) {
81
            return false;
82
        }
83
84
        $originalUser = $session->originalUser;
85
        $this->exchangeAuthUser($originalUser);
86
        /* @var \Zend\Session\Storage\StorageInterface $sessionStorage */
87
        $sessionStorage = $session->getManager()->getStorage();
88
        $sessionStorage->clear(self::SESSION_NAMESPACE);
89
90
        return true;
91
    }
92
93
    /**
94
     * Switch to another user.
95
     *
96
     * @param string|UserInterface $id user id of the user to switch to.
97
     * @param array $params Additional parameters to store in the session container.
98
     *
99
     * @return bool
100
     */
101
    public function switchUser($id, array $params = [])
0 ignored issues
show
Coding Style introduced by
function switchUser() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
102
    {
103
        if ($id instanceOf UserInterface) {
104
            $id = $id->getId();
105
        }
106
107
        $session = $this->getSessionContainer();
108
        if ($session->isSwitchedUser) {
109
            return false;
110
        }
111
112
        $session->isSwitchedUser = true;
113
        $session->originalUser = $this->exchangeAuthUser($id);
114
        $session->params       = $params;
115
116
        return true;
117
    }
118
119
    /**
120
     * Is the current user a switched one?
121
     *
122
     * @return bool
123
     */
124
    public function isSwitchedUser()
125
    {
126
        $session = $this->getSessionContainer();
127
128
        return isset($session->isSwitchedUser) && $session->isSwitchedUser;
129
    }
130
131
    /**
132
     * Set additional params.
133
     *
134
     * @param array $params
135
     * @param bool  $merge Merges with existing params.
136
     *
137
     * @return self
138
     */
139
    public function setSessionParams(array $params, $merge = false)
140
    {
141
        $session = $this->getSessionContainer();
142
143
        if (isset($session->params) && $merge) {
144
            $params = ArrayUtils::merge($session->params, $params);
145
        }
146
147
        $session->params = $params;
148
149
        return $this;
150
    }
151
152
    /**
153
     * Get additional params
154
     *
155
     * @return array
156
     */
157
    public function getSessionParams()
158
    {
159
        $session = $this->getSessionContainer();
160
161
        return isset($session->params) ? $session->params : [];
162
    }
163
164
    /**
165
     * Get a param.
166
     *
167
     * @param string $key
168
     * @param mixed $default Value to return if param $key is not set.
169
     *
170
     * @return null
171
     */
172
    public function getSessionParam($key, $default = null)
173
    {
174
        $params = $this->getSessionParams();
175
176
        return array_key_exists($key, $params) ? $params[$key] : $default;
177
    }
178
179
    /**
180
     * Set a param.
181
     *
182
     * @param string $key
183
     * @param mixed $value
184
     *
185
     * @return UserSwitcher
186
     */
187
    public function setSessionParam($key, $value)
188
    {
189
        return $this->setSessionParams([$key => $value], true);
190
    }
191
192
    /**
193
     * Gets the session container.
194
     *
195
     * @return Container
196
     */
197
    private function getSessionContainer()
198
    {
199
        if (!$this->sessionContainer) {
200
            $this->sessionContainer = new Container(self::SESSION_NAMESPACE);
201
        }
202
203
        return $this->sessionContainer;
204
    }
205
206
    /**
207
     * Exchanges the authenticated user in AuthenticationService.
208
     *
209
     * @param string $id
210
     *
211
     * @return string The id of the previously authenticated user.
212
     */
213
    private function exchangeAuthUser($id)
214
    {
215
        $storage = $this->auth->getStorage();
216
        $originalUserId = $storage->read();
217
        $this->auth->clearIdentity();
218
        $storage->write($id);
219
220
        return $originalUserId;
221
    }
222
}