UserService::create()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 9.2248
c 0
b 0
f 0
cc 5
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Service;
6
7
use App\Exception\UserException;
8
use App\Repository\UserRepository;
9
use Firebase\JWT\JWT;
10
11
class UserService extends BaseService
12
{
13
    const REDIS_KEY = 'user:%s';
14
15
    protected $userRepository;
16
17
    protected $redisService;
18
19
    public function __construct(UserRepository $userRepository, RedisService $redisService)
20
    {
21
        $this->userRepository = $userRepository;
22
        $this->redisService = $redisService;
23
    }
24
25
    protected function getUserFromDb(int $userId)
26
    {
27
        return $this->userRepository->getUser($userId);
28
    }
29
30
    public function getAll(): array
31
    {
32
        return $this->userRepository->getAll();
33
    }
34
35
    public function getOne(int $userId)
36
    {
37
        if (self::isRedisEnabled() === true) {
38
            $user = $this->getUserFromCache($userId);
39
        } else {
40
            $user = $this->getUserFromDb($userId);
41
        }
42
43
        return $user;
44
    }
45
46
    public function getUserFromCache(int $userId)
47
    {
48
        $redisKey = sprintf(self::REDIS_KEY, $userId);
49
        $key = $this->redisService->generateKey($redisKey);
50
        if ($this->redisService->exists($key)) {
51
            $data = $this->redisService->get($key);
52
            $user = json_decode(json_encode($data), false);
53
        } else {
54
            $user = $this->getUserFromDb($userId);
55
            $this->redisService->setex($key, $user);
56
        }
57
58
        return $user;
59
    }
60
61
    public function search(string $usersName): array
62
    {
63
        return $this->userRepository->search($usersName);
64
    }
65
66
    public function saveInCache($id, $user)
67
    {
68
        $redisKey = sprintf(self::REDIS_KEY, $id);
69
        $key = $this->redisService->generateKey($redisKey);
70
        $this->redisService->setex($key, $user);
71
    }
72
73
    public function deleteFromCache($userId)
74
    {
75
        $redisKey = sprintf(self::REDIS_KEY, $userId);
76
        $key = $this->redisService->generateKey($redisKey);
77
        $this->redisService->del($key);
78
    }
79
80
    public function create($input)
81
    {
82
        $user = new \stdClass();
83
        $data = json_decode(json_encode($input), false);
84
        if (!isset($data->name)) {
85
            throw new UserException('The field "name" is required.', 400);
86
        }
87
        if (!isset($data->email)) {
88
            throw new UserException('The field "email" is required.', 400);
89
        }
90
        if (!isset($data->password)) {
91
            throw new UserException('The field "password" is required.', 400);
92
        }
93
        $user->name = self::validateUserName($data->name);
94
        $user->email = self::validateEmail($data->email);
95
        $user->password = hash('sha512', $data->password);
96
        $this->userRepository->checkUserByEmail($user->email);
97
        $users = $this->userRepository->create($user);
98
        if (self::isRedisEnabled() === true) {
99
            $this->saveInCache($users->id, $users);
100
        }
101
102
        return $users;
103
    }
104
105
    public function update(array $input, int $userId)
106
    {
107
        $user = $this->getUserFromDb($userId);
108
        $data = json_decode(json_encode($input), false);
109
        if (!isset($data->name) && !isset($data->email)) {
110
            throw new UserException('Enter the data to update the user.', 400);
111
        }
112
        if (isset($data->name)) {
113
            $user->name = self::validateUserName($data->name);
114
        }
115
        if (isset($data->email)) {
116
            $user->email = self::validateEmail($data->email);
117
        }
118
        $users = $this->userRepository->update($user);
119
        if (self::isRedisEnabled() === true) {
120
            $this->saveInCache($users->id, $users);
121
        }
122
123
        return $users;
124
    }
125
126
    public function delete(int $userId): string
127
    {
128
        $this->getUserFromDb($userId);
129
        $this->userRepository->deleteUserTasks($userId);
130
        $data = $this->userRepository->delete($userId);
131
        if (self::isRedisEnabled() === true) {
132
            $this->deleteFromCache($userId);
133
        }
134
135
        return $data;
136
    }
137
138
    public function login(?array $input): string
139
    {
140
        $data = json_decode(json_encode($input), false);
141
        if (!isset($data->email)) {
142
            throw new UserException('The field "email" is required.', 400);
143
        }
144
        if (!isset($data->password)) {
145
            throw new UserException('The field "password" is required.', 400);
146
        }
147
        $password = hash('sha512', $data->password);
148
        $user = $this->userRepository->loginUser($data->email, $password);
149
        $token = [
150
            'sub' => $user->id,
151
            'email' => $user->email,
152
            'name' => $user->name,
153
            'iat' => time(),
154
            'exp' => time() + (7 * 24 * 60 * 60),
155
        ];
156
157
        return JWT::encode($token, getenv('SECRET_KEY'));
158
    }
159
}
160