Semaphore   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A acquire() 0 16 4
A release() 0 8 3
A destroy() 0 4 1
1
<?php
2
/**
3
 * Process Library
4
 * @author Tao <[email protected]>
5
 */
6
namespace Slince\Process\SystemV;
7
8
use Slince\Process\Exception\InvalidArgumentException;
9
use Slince\Process\Exception\RuntimeException;
10
11
class Semaphore
12
{
13
    use IpcKeyTrait;
14
15
    /**
16
     * Whether the semaphore is locked
17
     * @var boolean
18
     */
19
    protected $locked;
20
21
    /**
22
     * The resource that can be used to access the System V semaphore
23
     * @var resource
24
     */
25
    protected $semId;
26
27
    public function __construct($pathname = __FILE__, $maxAcquireNum = 1, $permission = 0666)
28
    {
29
        $ipcKey = $this->generateIpcKey($pathname);
30
        if (!($this->semId = sem_get($ipcKey, $maxAcquireNum, $permission))) {
31
            throw new RuntimeException("Cannot get semaphore identifier");
32
        }
33
    }
34
35
    /**
36
     * Acquires the lock
37
     * @param bool $blocking
38
     * @return bool
39
     */
40
    public function acquire($blocking = true)
41
    {
42
        //non-blocking requires php version greater than 5.6.1
43
        if (!$blocking) {
44
            if (version_compare(PHP_VERSION, '5.6.1') < 0) {
45
                throw new InvalidArgumentException("Semaphore requires php version greater than 5.6.1 when using blocking");
46
            }
47
            $result = sem_acquire($this->semId, !$blocking);
48
        } else {
49
            $result = sem_acquire($this->semId);
50
        }
51
        if ($result) {
52
            $this->locked = true;
53
        }
54
        return $result;
55
    }
56
57
    /**
58
     * Release the lock
59
     * @return bool
60
     */
61
    public function release()
62
    {
63
        if ($this->locked && sem_release($this->semId)) {
64
            $this->locked = false;
65
            return true;
66
        }
67
        return false;
68
    }
69
70
    /**
71
     * Destroy semaphore
72
     * @return void
73
     */
74
    public function destroy()
75
    {
76
        sem_remove($this->semId);
77
    }
78
}
79