|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace App\Service\Note; |
|
6
|
|
|
|
|
7
|
|
|
use App\Entity\Note; |
|
8
|
|
|
use App\Repository\NoteRepository; |
|
9
|
|
|
use App\Service\BaseService; |
|
10
|
|
|
use App\Service\RedisService; |
|
11
|
|
|
use App\Service\LoggerService; |
|
12
|
|
|
use Respect\Validation\Validator as v; |
|
13
|
|
|
|
|
14
|
|
|
abstract class Base extends BaseService |
|
15
|
|
|
{ |
|
16
|
|
|
private const REDIS_KEY = 'note:%s'; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct( |
|
19
|
|
|
protected NoteRepository $noteRepository, |
|
20
|
|
|
protected RedisService $redisService, |
|
21
|
16 |
|
protected LoggerService $loggerService |
|
22
|
|
|
) { |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
protected static function validateNoteName(string $name): string |
|
26
|
16 |
|
{ |
|
27
|
16 |
|
if (!v::length(1, 50)->validate($name)) { |
|
28
|
16 |
|
throw new \App\Exception\NoteException('The name of the note is invalid.', 400); |
|
29
|
16 |
|
} |
|
30
|
|
|
|
|
31
|
3 |
|
return $name; |
|
32
|
|
|
} |
|
33
|
3 |
|
|
|
34
|
1 |
|
protected function getOneFromCache(int $noteId): object |
|
35
|
|
|
{ |
|
36
|
|
|
$redisKey = sprintf(self::REDIS_KEY, $noteId); |
|
37
|
2 |
|
$key = $this->redisService->generateKey($redisKey); |
|
38
|
|
|
if ($this->redisService->exists($key)) { |
|
39
|
|
|
$note = $this->redisService->get($key); |
|
40
|
3 |
|
} else { |
|
41
|
|
|
$note = $this->getOneFromDb($noteId)->toJson(); |
|
42
|
3 |
|
$this->redisService->setex($key, $note); |
|
43
|
3 |
|
} |
|
44
|
3 |
|
|
|
45
|
2 |
|
return $note; |
|
46
|
|
|
} |
|
47
|
1 |
|
|
|
48
|
|
|
protected function getOneFromDb(int $noteId): Note |
|
49
|
|
|
{ |
|
50
|
|
|
return $this->noteRepository->checkAndGetNote($noteId); |
|
51
|
2 |
|
} |
|
52
|
|
|
|
|
53
|
|
|
protected function saveInCache(int $id, object $note): void |
|
54
|
6 |
|
{ |
|
55
|
|
|
$redisKey = sprintf(self::REDIS_KEY, $id); |
|
56
|
6 |
|
$key = $this->redisService->generateKey($redisKey); |
|
57
|
|
|
$this->redisService->setex($key, $note); |
|
58
|
|
|
} |
|
59
|
3 |
|
|
|
60
|
|
|
protected function deleteFromCache(int $noteId): void |
|
61
|
3 |
|
{ |
|
62
|
3 |
|
$redisKey = sprintf(self::REDIS_KEY, $noteId); |
|
63
|
3 |
|
$key = $this->redisService->generateKey($redisKey); |
|
64
|
3 |
|
$this->redisService->del([$key]); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|