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

ConnectionBasedLockAdapter::doGetLock()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 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
    protected function doGetLock(string $name)
20
    {
21
        if (!$this->connectionAdapter->exists($this->getLockFileName($name)))
22
        {
23
            return null;
24
        }
25
26
        return Lock::fromPayload($this->connectionAdapter->read($this->getLockFileName($name)));
27
    }
28
29
    protected function doAcquireLock(string $name): bool
30
    {
31
        $lockFileName = $this->getLockFileName($name);
32
        $payload = $this->getNewLockPayload($name);
33
34
        if ($this->connectionAdapter->exists($lockFileName))
35
        {
36
            return false;
37
        }
38
39
        $this->connectionAdapter->write($lockFileName, $payload);
40
41
        return true;
42
    }
43
44
    protected function doReleaseLock(string $name)
45
    {
46
        $this->connectionAdapter->unlink($this->getLockFileName($name));
47
    }
48
49
    protected function getLockFileName(string $lockName): string
50
    {
51
        return $lockName . '.lock';
52
    }
53
}
54