Completed
Push — master ( 030030...90a95a )
by Matze
10:56 queued 07:21
created

LoadUser::loadUserByUsername()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.4286
cc 2
eloc 5
nc 2
nop 1
crap 2
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\UsernameNotFoundException;
8
use Predis\Client;
9
10
/**
11
 * @api
12
 * @Service("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 UsernameNotFoundException
34
     */
35 2
    public function loadUserByUsername($username)
36
    {
37 2
        $userId = $this->redis->HGET(DatabaseUserProvider::REDIS_USER_NAMES, strtolower($username));
38
39 2
        if (empty($userId)) {
40 1
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
41
        }
42
43 1
        return $this->loadUserById($userId);
44
    }
45
46
    /**
47
     * @param integer $userId
48
     * @return UserVO
49
     */
50 1
    public function loadUserById($userId)
51
    {
52 1
        $redisUser = $this->redis->hgetall($this->getKey($userId));
53
54 1
        if (empty($redisUser)) {
55
            return new AnonymusUserVO();
56
        }
57
58 1
        $user                  = new UserVO();
59 1
        $user->id              = $userId;
60 1
        $user->username        = $redisUser['username'];
61 1
        $user->email           = isset($redisUser['email']) ? $redisUser['email'] : '';
62 1
        $user->password_hash   = $redisUser['password'];
63 1
        $user->one_time_secret = isset($redisUser['one_time_secret']) ? $redisUser['one_time_secret'] : null;
64 1
        $user->roles           = array_filter(explode(',', $redisUser['roles']));
65 1
        $user->avatar          = isset($redisUser['avatar']) ? $redisUser['avatar'] : '';
66
67 1
        return $user;
68
    }
69
70
    /**
71
     * @param integer $userId
72
     * @return string
73
     */
74 1
    private function getKey($userId)
75
    {
76 1
        return sprintf(DatabaseUserProvider::REDIS_USER, $userId);
77
    }
78
}
79