Completed
Push — master ( 83bd2d...9517e2 )
by Arne
03:10
created

ConnectionBasedLockAdapter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 2
dl 0
loc 48
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A isLocked() 0 4 1
A acquireLock() 0 13 3
A releaseLock() 0 11 2
A getLockFileName() 0 4 1
1
<?php
2
3
namespace Archivr\LockAdapter;
4
5
use Archivr\ConnectionAdapter\ConnectionAdapterInterface;
6
7
class ConnectionBasedLockAdapter extends AbstractLockAdapter
8
{
9
    /**
10
     * @var ConnectionAdapterInterface
11
     */
12
    protected $connectionAdapter;
13
14
    public function __construct(ConnectionAdapterInterface $connectionAdapter)
15
    {
16
        $this->connectionAdapter = $connectionAdapter;
17
    }
18
19
    public function isLocked(string $name): bool
20
    {
21
        return $this->connectionAdapter->exists($name . '.lock');
22
    }
23
24
    public function acquireLock(string $name): bool
25
    {
26
        $lockFileName = $this->getLockFileName($name);
27
28
        if (!$this->hasLock($name) && !$this->connectionAdapter->exists($lockFileName))
29
        {
30
            $this->connectionAdapter->write($lockFileName, $this->getLockLabel());
31
32
            $this->acquiredLocks[] = $name;
33
        }
34
35
        return $this->hasLock($name);
36
    }
37
38
    public function releaseLock(string $name): bool
39
    {
40
        if ($index = array_search($name, $this->acquiredLocks))
41
        {
42
            $this->connectionAdapter->unlink($this->getLockFileName($name));
43
44
            unset($this->acquiredLocks[$index]);
45
        }
46
47
        return !$this->hasLock($name);
48
    }
49
50
    protected function getLockFileName(string $lockName): string
51
    {
52
        return $lockName . '.lock';
53
    }
54
}
55