Completed
Pull Request — master (#361)
by
unknown
03:09
created

TerminateUserSessionsService::getUser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
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\SessionHistory;
13
14
15
use Da\User\Contracts\ServiceInterface;
16
use Da\User\Event\SessionEvent;
17
use Da\User\Model\SessionHistory;
18
use Da\User\Model\User;
19
use Da\User\Traits\ContainerAwareTrait;
20
use Da\User\Traits\ModuleAwareTrait;
21
use yii\web\Session;
22
use Yii;
23
24
class TerminateUserSessionsService implements ServiceInterface
25
{
26
    use ContainerAwareTrait;
27
    use ModuleAwareTrait;
28
29
    protected $userId;
30
    protected $session;
31
    protected $excludeCurrentSession;
32
33
    public function __construct($userId, Session $session, $excludeCurrentSession = true)
34
    {
35
        $this->userId = intval($userId);
36
        $this->session = $session;
37
        $this->excludeCurrentSession = $excludeCurrentSession;
38
    }
39
40
    public function run()
41
    {
42
        $user = $this->getUser($this->userId);
43
        $sessionIds = $this->getSessionIds($user->id);
44
45
        Yii::$app->db->transaction(function () use ($sessionIds, $user) {
46
            /** @var SessionEvent $event */
47
            $event = $this->make(SessionEvent::class, [$user]);
48
49
            $user->trigger(SessionEvent::EVENT_BEFORE_TERMINATE_USER_SESSIONS, $event);
50
51
            $this->make(TerminateSessionsServiceInterface::class, [$sessionIds])->run();
52
53
            $user->updateAttributes([
54
                'auth_key' => Yii::$app->security->generateRandomString(),
55
            ]);
56
57
            if ($this->excludeCurrentUser()) {
58
                Yii::$app->user->switchIdentity(
59
                    $user,
60
                    $this->getModule()->rememberLoginLifespan
61
                );
62
            }
63
64
            $user->trigger(SessionEvent::EVENT_AFTER_TERMINATE_USER_SESSIONS, $event);
65
        });
66
67
        return true;
68
    }
69
70
    /**
71
     * @param int $userId
72
     * @return User
73
     */
74
    protected function getUser($userId)
75
    {
76
        return ($this->make(User::class))::findOne($userId);
77
    }
78
79
    /**
80
     * @param $userId
81
     * @return int[]
82
     */
83
    protected function getSessionIds($userId)
84
    {
85
        /** @var SessionHistory $sessionHistory */
86
        $sessionHistory = $this->make(SessionHistory::class);
87
        $sessionIds = $sessionHistory::find()->whereUserId($userId)->whereActive()->selectSessionId()->column();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\db\ActiveQueryInterface as the method whereUserId() does only exist in the following implementations of said interface: Da\User\Query\ProfileQuery, Da\User\Query\SessionHistoryQuery, Da\User\Query\TokenQuery.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
88
89
        if ($this->excludeCurrentUser()) {
90
            foreach ($sessionIds as $key => $sessionId) {
91
                if ($sessionId === $this->session->id) {
92
                    unset($sessionIds[$key]);
93
                    break;
94
                }
95
            }
96
        }
97
98
        return $sessionIds;
99
    }
100
101
    protected function excludeCurrentUser()
102
    {
103
        return $this->excludeCurrentSession && $this->userId === Yii::$app->user->id;
104
    }
105
}