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

AbstractLockAdapter   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 0
dl 0
loc 78
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A isLocked() 0 4 2
A hasLock() 0 4 1
A acquireLock() 0 18 3
A releaseLock() 0 14 3
A __destruct() 0 4 1
A releaseAcquiredLocks() 0 9 2
A getLockLabel() 0 7 1
doesLockExist() 0 1 ?
doAcquireLock() 0 1 ?
doReleaseLock() 0 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