Completed
Push — master ( 2cde75...6c52d6 )
by Arne
02:04
created

StorageBasedLockAdapter   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 3
dl 0
loc 64
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A doGetLock() 0 9 2
B doAcquireLock() 0 31 5
A doReleaseLock() 0 4 1
A getLockFileName() 0 4 1
1
<?php
2
3
namespace Storeman\LockAdapter;
4
5
use Storeman\StorageAdapter\StorageAdapterInterface;
6
7
class StorageBasedLockAdapter extends AbstractLockAdapter
8
{
9
    /**
10
     * @var StorageAdapterInterface
11
     */
12
    protected $storageAdapter;
13
14
    public function __construct(StorageAdapterInterface $storageAdapter)
15
    {
16
        $this->storageAdapter = $storageAdapter;
17
    }
18
19
    protected function doGetLock(string $name): ?Lock
20
    {
21
        if (!$this->storageAdapter->exists($this->getLockFileName($name)))
22
        {
23
            return null;
24
        }
25
26
        return Lock::fromPayload($this->storageAdapter->read($this->getLockFileName($name)));
27
    }
28
29
    protected function doAcquireLock(string $name, int $timeout = null): bool
30
    {
31
        $lockFileName = $this->getLockFileName($name);
32
        $payload = $this->getNewLockPayload($name);
33
34
        $started = time();
35
36
        while(true)
37
        {
38
            if (!$this->storageAdapter->exists($lockFileName))
39
            {
40
                $this->storageAdapter->write($lockFileName, $payload);
41
42
                return true;
43
            }
44
45
            // timeout not reached: sleep another round and try againg
46
            if ($timeout === null || ($started + $timeout) < time())
47
            {
48
                sleep(3);
49
            }
50
51
            // timeout reached: return false
52
            else
53
            {
54
                return false;
55
            }
56
        }
57
58
        return false;
59
    }
60
61
    protected function doReleaseLock(string $name): void
62
    {
63
        $this->storageAdapter->unlink($this->getLockFileName($name));
64
    }
65
66
    protected function getLockFileName(string $lockName): string
67
    {
68
        return $lockName . '.lock';
69
    }
70
}
71