Base::saveInCache()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
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 5
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Service\Task;
6
7
use App\Entity\Task;
8
use App\Repository\TaskRepository;
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 = 'task:%s:user:%s';
17
18
    public function __construct(
19
        protected TaskRepository $taskRepository,
20
        protected RedisService $redisService,
21 19
        protected LoggerService $loggerService
22
    ) {
23
    }
24
25
    protected function getTaskRepository(): TaskRepository
26 19
    {
27 19
        return $this->taskRepository;
28 19
    }
29 19
30
    protected static function validateTaskName(string $name): string
31 4
    {
32
        if (!v::length(1, 100)->validate($name)) {
33 4
            throw new \App\Exception\TaskException('Invalid name.', 400);
34 1
        }
35
36
        return $name;
37 3
    }
38
39
    protected static function validateTaskStatus(int $status): int
40 2
    {
41
        if (!v::numeric()->between(0, 1)->validate($status)) {
42 2
            throw new \App\Exception\TaskException('Invalid status', 400);
43 1
        }
44
45
        return $status;
46 1
    }
47
48
    protected function getTaskFromCache(int $taskId, int $userId): object
49 3
    {
50
        $redisKey = sprintf(self::REDIS_KEY, $taskId, $userId);
51 3
        $key = $this->redisService->generateKey($redisKey);
52 3
        if ($this->redisService->exists($key)) {
53 3
            $task = $this->redisService->get($key);
54 2
        } else {
55
            $task = $this->getTaskFromDb($taskId, $userId)->toJson();
56 1
            $this->redisService->setex($key, $task);
57
        }
58
59
        return $task;
60 2
    }
61
62
    protected function getTaskFromDb(int $taskId, int $userId): Task
63 7
    {
64
        return $this->taskRepository->checkAndGetTask($taskId, $userId);
65 7
    }
66
67
    protected function saveInCache(int $taskId, int $userId, object $task): void
68 2
    {
69
        $redisKey = sprintf(self::REDIS_KEY, $taskId, $userId);
70 2
        $key = $this->redisService->generateKey($redisKey);
71 2
        $this->redisService->setex($key, $task);
72 2
    }
73 2
74
    protected function deleteFromCache(int $taskId, int $userId): void
75 1
    {
76
        $redisKey = sprintf(self::REDIS_KEY, $taskId, $userId);
77 1
        $key = $this->redisService->generateKey($redisKey);
78 1
        $this->redisService->del([$key]);
79 1
    }
80
}
81