Passed
Push — master ( 0b75f0...6b8772 )
by Fernando
17:35
created

Base::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
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 3
dl 0
loc 8
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\Exception\NoteException;
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
    /** @var NoteRepository */
19
    protected $noteRepository;
20
21
    /** @var RedisService */
22
    protected $redisService;
23
24
    /** @var LoggerService */
25
    protected $loggerService;
26
27 16
    public function __construct(
28
        NoteRepository $noteRepository,
29
        RedisService $redisService,
30
        LoggerService $loggerService
31
    ) {
32 16
        $this->noteRepository = $noteRepository;
33 16
        $this->redisService = $redisService;
34 16
        $this->loggerService = $loggerService;
35 16
    }
36
37 3
    protected static function validateNoteName(string $name): string
38
    {
39 3
        if (!v::length(1, 50)->validate($name)) {
40 1
            throw new NoteException('The name of the note is invalid.', 400);
41
        }
42
43 2
        return $name;
44
    }
45
46 3
    protected function getOneFromCache(int $noteId): object
47
    {
48 3
        $redisKey = sprintf(self::REDIS_KEY, $noteId);
49 3
        $key = $this->redisService->generateKey($redisKey);
50 3
        if ($this->redisService->exists($key)) {
51 2
            $note = $this->redisService->get($key);
52
        } else {
53 1
            $note = $this->getOneFromDb($noteId)->getData();
54
            $this->redisService->setex($key, $note);
55
        }
56
57 2
        return $note;
58
    }
59
60 6
    protected function getOneFromDb(int $noteId): \App\Entity\Note
61
    {
62 6
        return $this->noteRepository->checkAndGetNote($noteId);
63
    }
64
65 3
    protected function saveInCache(int $id, object $note): void
66
    {
67 3
        $redisKey = sprintf(self::REDIS_KEY, $id);
68 3
        $key = $this->redisService->generateKey($redisKey);
69 3
        $this->redisService->setex($key, $note);
70 3
    }
71
72 1
    protected function deleteFromCache(int $noteId): void
73
    {
74 1
        $redisKey = sprintf(self::REDIS_KEY, $noteId);
75 1
        $key = $this->redisService->generateKey($redisKey);
76 1
        $this->redisService->del([$key]);
77 1
    }
78
}
79