Completed
Push — master ( 5a5b2e...66ec7e )
by Matze
04:12
created

LoadUser::buildUserVO()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

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