Completed
Push — master ( 9913ec...45b4e9 )
by Arne
01:45
created

AbstractLockAdapter::getIdentity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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
    /**
13
     * @var string
14
     */
15
    protected $identity;
16
17
    public function isLocked(string $name): bool
18
    {
19
        return $this->hasLock($name) || $this->doGetLock($name) !== null;
20
    }
21
22
    public function hasLock(string $name): bool
23
    {
24
        return isset($this->lockDepthMap[$name]);
25
    }
26
27
    public function getLock(string $name)
28
    {
29
        return $this->doGetLock($name);
30
    }
31
32
    public function acquireLock(string $name): bool
33
    {
34
        if (!isset($this->lockDepthMap[$name]))
35
        {
36
            $success = $this->doAcquireLock($name);
37
38
            if (!$success)
39
            {
40
                return false;
41
            }
42
43
            $this->lockDepthMap[$name] = 0;
44
        }
45
46
        $this->lockDepthMap[$name]++;
47
48
        return true;
49
    }
50
51
    public function releaseLock(string $name): bool
52
    {
53
        if (isset($this->lockDepthMap[$name]))
54
        {
55
            if (--$this->lockDepthMap[$name] === 0)
56
            {
57
                $this->doReleaseLock($name);
58
59
                unset($this->lockDepthMap[$name]);
60
            }
61
        }
62
63
        return true;
64
    }
65
66
    public function setIdentity(string $identity): LockAdapterInterface
67
    {
68
        $this->identity = $identity;
69
70
        return $this;
71
    }
72
73
    public function getIdentity(): string
74
    {
75
        return $this->identity;
76
    }
77
78
    public function __destruct()
79
    {
80
        $this->releaseAcquiredLocks();
81
    }
82
83
    protected function releaseAcquiredLocks()
84
    {
85
        foreach (array_keys($this->lockDepthMap) as $lockName)
86
        {
87
            $this->doReleaseLock($lockName);
88
        }
89
90
        $this->lockDepthMap = [];
91
    }
92
93
    protected function getNewLockPayload(string $name): string
94
    {
95
        return (new Lock($name, $this->identity))->getPayload();
96
    }
97
98
    abstract protected function doGetLock(string $name);
99
    abstract protected function doAcquireLock(string $name): bool;
100
    abstract protected function doReleaseLock(string $name);
101
}
102