SwitchIdentityService   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 7
dl 0
loc 45
ccs 0
cts 27
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A run() 0 25 3
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-usuario project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\User\Service;
13
14
use Da\User\Contracts\ServiceInterface;
15
use Da\User\Controller\AdminController;
16
use Da\User\Event\UserEvent;
17
use Da\User\Model\User;
18
use Da\User\Module;
19
use Da\User\Query\UserQuery;
20
use Da\User\Traits\ContainerAwareTrait;
21
use Yii;
22
use yii\web\ForbiddenHttpException;
23
use yii\web\IdentityInterface;
24
25
class SwitchIdentityService implements ServiceInterface
26
{
27
    use ContainerAwareTrait;
28
29
    protected $controller;
30
    protected $switchIdentitySessionKey;
31
    protected $userId;
32
    protected $userQuery;
33
34
    public function __construct(AdminController $controller, UserQuery $userQuery, $userId = null)
35
    {
36
        /** @var Module $module */
37
        $module = $controller->module;
38
        $this->controller = $controller;
39
        $this->switchIdentitySessionKey = $module->switchIdentitySessionKey;
40
        $this->userId = $userId;
41
        $this->userQuery = $userQuery;
42
    }
43
44
    public function run()
45
    {
46
        $session = Yii::$app->session;
47
        if (null === $this->userId) { // switch back identities
48
            $user = $this->userQuery->whereId($session->get($this->switchIdentitySessionKey))->one();
49
            $session->remove($this->switchIdentitySessionKey);
50
        } else {
51
            /** @var User $identity */
52
            $identity = Yii::$app->user->identity;
53
            if (!$identity->getIsAdmin()) {
54
                // Only admins allowed on module. Developers can override the service and implement different
55
                // approach. For example, by roles other than, and including, admin.
56
                throw new ForbiddenHttpException();
57
            }
58
            $user = $this->userQuery->whereId($this->userId)->one();
59
            $session->set($this->switchIdentitySessionKey, Yii::$app->user->id);
60
        }
61
62
        $event = $this->make(UserEvent::class, [$user]);
63
64
        $this->controller->trigger(UserEvent::EVENT_BEFORE_SWITCH_IDENTITY, $event);
65
        /** @var IdentityInterface $user */
66
        Yii::$app->user->switchIdentity($user, $session->timeout);
67
        $this->controller->trigger(UserEvent::EVENT_AFTER_SWITCH_IDENTITY, $event);
68
    }
69
}
70