Completed
Push — master ( fa0d52...fef7a6 )
by Arne
01:59
created

StorageBasedLockAdapter::doAcquireLock()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 31
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.439
c 0
b 0
f 0
cc 5
eloc 13
nc 4
nop 2
1
<?php
2
3
namespace Archivr\LockAdapter;
4
5
use Archivr\StorageDriver\StorageDriverInterface;
6
7
class StorageBasedLockAdapter extends AbstractLockAdapter
8
{
9
    /**
10
     * @var StorageDriverInterface
11
     */
12
    protected $storageDriver;
13
14
    public function __construct(StorageDriverInterface $storageDriver)
15
    {
16
        $this->storageDriver = $storageDriver;
17
    }
18
19
    protected function doGetLock(string $name)
20
    {
21
        if (!$this->storageDriver->exists($this->getLockFileName($name)))
22
        {
23
            return null;
24
        }
25
26
        return Lock::fromPayload($this->storageDriver->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->storageDriver->exists($lockFileName))
39
            {
40
                $this->storageDriver->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)
62
    {
63
        $this->storageDriver->unlink($this->getLockFileName($name));
64
    }
65
66
    protected function getLockFileName(string $lockName): string
67
    {
68
        return $lockName . '.lock';
69
    }
70
}
71