Passed
Push — master ( 366c47...c0f740 )
by Nico
26:57 queued 04:36
created

LockManager::getLockPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 2
dl 0
loc 7
ccs 6
cts 6
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stu\Module\Tick\Lock;
6
7
use RuntimeException;
8
use Stu\Module\Config\StuConfigInterface;
9
10
final class LockManager implements LockManagerInterface
11
{
12
    private StuConfigInterface $config;
13
14 2
    public function __construct(StuConfigInterface $config)
15
    {
16 2
        $this->config = $config;
17
    }
18
19 1
    public function setLock(int $batchGroupId, LockTypeEnum $type): void
20
    {
21 1
        $result = @touch($this->getLockPath($batchGroupId, $type));
22
23 1
        if ($result === false) {
24
            throw new RuntimeException(sprintf(
25
                'lock with batchGroupId "%d" of type "%d" could not be created',
26
                $type->value,
27
                $batchGroupId
28
            ));
29
        }
30
    }
31
32 1
    public function clearLock(int $batchGroupId, LockTypeEnum $type): void
33
    {
34 1
        $result = @unlink($this->getLockPath($batchGroupId, $type));
35
36 1
        if ($result === false) {
37
            throw new RuntimeException(sprintf(
38
                'lock with batchGroupId "%d" of type "%d" could not be deleted',
39
                $type->value,
40
                $batchGroupId
41
            ));
42
        }
43
    }
44
45 1
    public function isLocked(int $entityId, LockTypeEnum $type): bool
46
    {
47 1
        return @file_exists($this->getLockPath($entityId % $this->getGroupCount($type) + 1, $type));
48
    }
49
50 1
    private function getLockPath(int $batchGroupId, LockTypeEnum $type): string
51
    {
52 1
        return sprintf(
53 1
            '%s/%s_%d.lock',
54 1
            $this->config->getGameSettings()->getTempDir(),
55 1
            $type->getName(),
56 1
            $batchGroupId
57 1
        );
58
    }
59
60 1
    private function getGroupCount(LockTypeEnum $type): int
61
    {
62
        switch ($type) {
63 1
            case LockTypeEnum::COLONY_GROUP:
64 1
                return $this->config->getGameSettings()->getColonySettings()->getTickWorker();
65
            case LockTypeEnum::SHIP_GROUP:
0 ignored issues
show
introduced by
The function implicitly returns null when this case condition does not match. This is incompatible with the type-hinted return integer. Consider adding a default case to the switch.
Loading history...
66
                return 1;
67
        }
68
    }
69
}
70