Base::deleteFromCache()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
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