MutexAdapter::acquire()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 4
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Mutex Library.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace AMF\Mutex;
11
12
use AMF\Mutex\MutexInterface;
13
14
/**
15
 * Adapter to adapt mutex to current context.
16
 *
17
 * @author Amine Fattouch <[email protected]>
18
 */
19
class MutexAdapter
20
{
21
    /**
22
     * @var MutexInterface
23
     */
24
    protected $mutex;
25
26
    /**
27
     * @var integer
28
     */
29
    protected $attemptTotal;
30
31
    /**
32
     * @var integer
33
     */
34
    protected $wait;
35
36
    /**
37
     * @var string
38
     */
39
    protected $prefix;
40
41
    /**
42
     *
43
     * @param MutexInterface $mutex
44
     * @param integer        $attemptTotal
45
     * @param integer        $wait
46
     * @param string         $prefix
47
     */
48
    public function __construct(MutexInterface $mutex, $attemptTotal = 10, $wait = 1, $prefix = 'worker_mutex')
49
    {
50
        $this->mutex        = $mutex;
51
        $this->attemptTotal = $attemptTotal;
52
        $this->wait         = $wait;
53
        $this->prefix       = $prefix;
54
    }
55
56
    /**
57
     * Acquires access to Semaphore.
58
     *
59
     * @param string  $key
60
     * @param integer $ttl
61
     *
62
     * @return string
63
     */
64
    public function acquire($key, $ttl = 60)
65
    {
66
        $generatedKey = $this->generateKey($key);
67
        $attemptTotal = $this->attemptTotal;
68
        $mutex        = $this->mutex;
69
70
        while ($attemptTotal > 0 && !$acquired = $mutex->acquire($generatedKey, $ttl)) {
71
            $attemptTotal --;
72
            sleep($this->wait);
73
        }
74
75
        if (isset($acquired) === false) {
76
            throw new \RuntimeException('Can\'t acquire the mutex. it\'s already taken by another process.');
77
        }
78
79
        return $generatedKey;
80
    }
81
82
    /**
83
     * Releases access to Semaphore.
84
     *
85
     * @param string $key
86
     */
87
    public function release($key)
88
    {
89
        $generatedKey = $this->generateKey($key);
90
91
        if ($this->mutex->release($generatedKey) === false) {
92
            throw new \RuntimeException('Can\'t relase the mutex. you must acquire it first.');
93
        }
94
    }
95
96
    /**
97
     * Generates a key with prefix.
98
     *
99
     * @param string $key
100
     *
101
     * @return string
102
     */
103
    protected function generateKey($key)
104
    {
105
        return $this->prefix.$key;
106
    }
107
}
108