Completed
Pull Request — master (#40)
by
unknown
09:28
created

Mutex   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 86.36%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 1
dl 0
loc 84
ccs 19
cts 22
cp 0.8636
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A acquireLock() 0 11 3
A releaseLock() 0 13 4
A isAcquired() 0 4 1
A isLocked() 0 4 1
1
<?php
2
/**
3
 * This file is part of ninja-mutex.
4
 *
5
 * (C) Kamil Dziedzic <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace NinjaMutex;
11
12
use NinjaMutex\Lock\LockInterface;
13
14
/**
15
 * Mutex
16
 *
17
 * @author Kamil Dziedzic <[email protected]>
18
 */
19
class Mutex
20
{
21
    /**
22
     * Lock implementor
23
     *
24
     * @var LockInterface
25
     */
26
    protected $lockImplementor;
27
28
    /**
29
     * Name of lock
30
     *
31
     * @var string
32
     */
33
    protected $name;
34
35
    /**
36
     * Lock counter to protect against recursive deadlock
37
     *
38
     * @var integer
39
     */
40
    protected $counter = 0;
41
42
    /**
43
     * @param string        $name
44
     * @param LockInterface $lockImplementor
45
     */
46 44
    public function __construct($name, LockInterface $lockImplementor)
47
    {
48 44
        $this->name = $name;
49 44
        $this->lockImplementor = $lockImplementor;
50 44
    }
51
52
    /**
53
     * @param  int|null $timeout
54
     * @return bool
55
     */
56 20
    public function acquireLock($timeout = null)
57
    {
58 20
        if ($this->counter > 0 ||
59 20
            $this->lockImplementor->acquireLock($this->name, $timeout)) {
60 20
            $this->counter++;
61
62 20
            return true;
63
        }
64
65
        return false;
66
    }
67
68
    /**
69
     * @return bool
70
     */
71 12
    public function releaseLock()
72
    {
73 12
        if ($this->counter > 0) {
74 12
            $this->counter--;
75 12
            if ($this->counter > 0 ||
76 12
                $this->lockImplementor->releaseLock($this->name)) {
77 12
                return true;
78
            }
79
            $this->counter++;
80
        }
81
82
        return false;
83
    }
84
85
    /**
86
     * Check if Mutex is acquired
87
     *
88
     * @return bool
89
     */
90 20
    public function isAcquired()
91
    {
92 20
        return $this->counter > 0;
93
    }
94
95
    /**
96
     * @return bool
97
     */
98 19
    public function isLocked()
99
    {
100 19
        return $this->lockImplementor->isLocked($this->name);
101
    }
102
}
103