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

StorageBasedLockAdapter::getLockFileName()   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 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