|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace App\Service\User; |
|
6
|
|
|
|
|
7
|
|
|
use App\Entity\User; |
|
8
|
|
|
use App\Repository\UserRepository; |
|
9
|
|
|
use App\Service\BaseService; |
|
10
|
|
|
use App\Service\LoggerService; |
|
11
|
|
|
use App\Service\RedisService; |
|
12
|
|
|
use Respect\Validation\Validator as v; |
|
13
|
|
|
|
|
14
|
|
|
abstract class Base extends BaseService |
|
15
|
|
|
{ |
|
16
|
|
|
private const REDIS_KEY = 'user:%s'; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct( |
|
19
|
|
|
protected UserRepository $userRepository, |
|
20
|
|
|
protected RedisService $redisService, |
|
21
|
23 |
|
protected LoggerService $loggerService |
|
22
|
|
|
) { |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
protected static function validateUserName(string $name): string |
|
26
|
23 |
|
{ |
|
27
|
23 |
|
if (!v::alnum('ÁÉÍÓÚÑáéíóúñ.')->length(1, 100)->validate($name)) { |
|
28
|
23 |
|
throw new \App\Exception\UserException('Invalid name.', 400); |
|
29
|
23 |
|
} |
|
30
|
|
|
|
|
31
|
5 |
|
return $name; |
|
32
|
|
|
} |
|
33
|
5 |
|
|
|
34
|
1 |
|
protected static function validateEmail(string $emailValue): string |
|
35
|
|
|
{ |
|
36
|
|
|
$email = filter_var($emailValue, FILTER_SANITIZE_EMAIL); |
|
37
|
4 |
|
if (!v::email()->validate($email)) { |
|
38
|
|
|
throw new \App\Exception\UserException('Invalid email', 400); |
|
39
|
|
|
} |
|
40
|
4 |
|
|
|
41
|
|
|
return (string) $email; |
|
42
|
4 |
|
} |
|
43
|
4 |
|
|
|
44
|
1 |
|
protected function getUserFromCache(int $userId): object |
|
45
|
|
|
{ |
|
46
|
|
|
$redisKey = sprintf(self::REDIS_KEY, $userId); |
|
47
|
3 |
|
$key = $this->redisService->generateKey($redisKey); |
|
48
|
|
|
if ($this->redisService->exists($key)) { |
|
49
|
|
|
$data = $this->redisService->get($key); |
|
50
|
3 |
|
$user = json_decode((string) json_encode($data), false); |
|
51
|
|
|
} else { |
|
52
|
3 |
|
$user = $this->getUserFromDb($userId)->toJson(); |
|
53
|
3 |
|
$this->redisService->setex($key, $user); |
|
54
|
3 |
|
} |
|
55
|
2 |
|
|
|
56
|
2 |
|
return $user; |
|
57
|
|
|
} |
|
58
|
1 |
|
|
|
59
|
|
|
protected function getUserFromDb(int $userId): User |
|
60
|
|
|
{ |
|
61
|
|
|
return $this->userRepository->checkAndGetUser($userId); |
|
62
|
2 |
|
} |
|
63
|
|
|
|
|
64
|
|
|
protected function saveInCache(int $id, object $user): void |
|
65
|
5 |
|
{ |
|
66
|
|
|
$redisKey = sprintf(self::REDIS_KEY, $id); |
|
67
|
5 |
|
$key = $this->redisService->generateKey($redisKey); |
|
68
|
|
|
$this->redisService->setex($key, $user); |
|
69
|
|
|
} |
|
70
|
2 |
|
|
|
71
|
|
|
protected function deleteFromCache(int $userId): void |
|
72
|
2 |
|
{ |
|
73
|
2 |
|
$redisKey = sprintf(self::REDIS_KEY, $userId); |
|
74
|
2 |
|
$key = $this->redisService->generateKey($redisKey); |
|
75
|
2 |
|
$this->redisService->del([$key]); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|