LoadUser   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 75
ccs 25
cts 25
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A loadUserByUsername() 0 10 2
A loadUserById() 0 10 2
A getKey() 0 4 1
A buildUserVO() 0 13 1
1
<?php
2
3
namespace BrainExe\Core\Authentication;
4
5
use BrainExe\Core\Annotations\Service;
6
use BrainExe\Core\Authentication\Exception\UserNotFoundException;
7
use BrainExe\Core\Redis\Predis;
8
9
/**
10
 * @api
11
 * @Service
12
 */
13
class LoadUser
14
{
15
    /**
16
     * @var Predis
17
     */
18
    private $redis;
19
20
    /**
21
     * @param Predis $redis
22
     */
23 4
    public function __construct(Predis $redis)
24
    {
25 4
        $this->redis = $redis;
26 4
    }
27
28
    /**
29
     * @param string $username
30
     * @return UserVO
31
     * @throws UserNotFoundException
32
     */
33 2
    public function loadUserByUsername(string $username) : UserVO
34
    {
35 2
        $userId = $this->redis->hget(UserProvider::REDIS_USER_NAMES, mb_strtolower($username));
36
37 2
        if (empty($userId)) {
38 1
            throw new UserNotFoundException(sprintf('Username "%s" does not exist.', $username));
39
        }
40
41 1
        return $this->loadUserById($userId);
42
    }
43
44
    /**
45
     * @param int $userId
46
     * @return UserVO
47
     * @throws UserNotFoundException
48
     */
49 2
    public function loadUserById(int $userId) : UserVO
50
    {
51 2
        $redisUser = $this->redis->hgetall($this->getKey($userId));
52
53 2
        if (empty($redisUser)) {
54 1
            throw new UserNotFoundException(sprintf('User "%d" does not exist.', $userId));
55
        }
56
57 1
        return $this->buildUserVO($userId, $redisUser);
58
    }
59
60
    /**
61
     * @param int $userId
62
     * @return string
63
     */
64 2
    private function getKey(int $userId) : string
65
    {
66 2
        return sprintf(UserProvider::REDIS_USER, $userId);
67
    }
68
69
    /**
70
     * @param int $userId
71
     * @param $redisUser
72
     * @return UserVO
73
     */
74 1
    private function buildUserVO(int $userId, array $redisUser) : UserVO
75
    {
76 1
        $user                  = new UserVO();
77 1
        $user->id              = $userId;
78 1
        $user->username        = $redisUser['username'];
79 1
        $user->email           = $redisUser['email'] ?? '';
80 1
        $user->password_hash   = $redisUser['password'];
81 1
        $user->one_time_secret = $redisUser['one_time_secret'] ?? null;
82 1
        $user->roles           = array_filter(explode(',', $redisUser['roles']));
83 1
        $user->avatar          = $redisUser['avatar'] ?? UserVO::DEFAULT_AVATAR;
84
85 1
        return $user;
86
    }
87
}
88