Completed
Push — master ( f2b67d...98a2b4 )
by Arne
01:46
created

AbstractLockAdapter::releaseLock()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
3
namespace Archivr\LockAdapter;
4
5
abstract class AbstractLockAdapter implements LockAdapterInterface
6
{
7
    /**
8
     * @var int[]
9
     */
10
    protected $lockDepthMap = [];
11
12
    public function isLocked(string $name): bool
13
    {
14
        return $this->hasLock($name) || $this->doesLockExist($name);
15
    }
16
17
    public function hasLock(string $name): bool
18
    {
19
        return isset($this->lockDepthMap[$name]);
20
    }
21
22
    public function acquireLock(string $name): bool
23
    {
24
        if (!isset($this->lockDepthMap[$name]))
25
        {
26
            $success = $this->doAcquireLock($name);
27
28
            if (!$success)
29
            {
30
                return false;
31
            }
32
33
            $this->lockDepthMap[$name] = 0;
34
        }
35
36
        $this->lockDepthMap[$name]++;
37
38
        return true;
39
    }
40
41
    public function releaseLock(string $name): bool
42
    {
43
        if (isset($this->lockDepthMap[$name]))
44
        {
45
            if (--$this->lockDepthMap[$name] === 0)
46
            {
47
                $this->doReleaseLock($name);
48
49
                unset($this->lockDepthMap[$name]);
50
            }
51
        }
52
53
        return true;
54
    }
55
56
    public function __destruct()
57
    {
58
        $this->releaseAcquiredLocks();
59
    }
60
61
    protected function releaseAcquiredLocks()
62
    {
63
        foreach (array_keys($this->lockDepthMap) as $lockName)
64
        {
65
            $this->doReleaseLock($lockName);
66
        }
67
68
        $this->lockDepthMap = [];
69
    }
70
71
    protected function getLockLabel(): string
72
    {
73
        return json_encode([
74
            'acquired' => time(),
75
            'user' => get_current_user()
76
        ]);
77
    }
78
79
    abstract protected function doesLockExist(string $name): bool;
80
    abstract protected function doAcquireLock(string $name): bool;
81
    abstract protected function doReleaseLock(string $name);
82
}
83