Completed
Push — master ( e1edf3...77b1ac )
by Akihito
02:27
created

AbstractQueue::isExceedsLimit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
namespace Ackintosh\Snidel;
3
4
use Ackintosh\Snidel\IpcKey;
5
6
abstract class AbstractQueue
7
{
8
    /** @var int */
9
    protected $ownerPid;
10
11
    /** @var \Ackintosh\Snidel\IpcKey */
12
    protected $ipcKey;
13
14
    /** @var resource */
15
    protected $id;
16
17
    /** @var array */
18
    protected $stat;
19
20
    /** @var int */
21
    protected $queuedCount = 0;
22
23
    /** @var int */
24
    protected $dequeuedCount = 0;
25
26
    public function __construct($ownerPid)
27
    {
28
        $this->ownerPid = $ownerPid;
29
        $this->ipcKey   = new IpcKey($this->ownerPid, str_replace('\\', '_', get_class($this)));
30
        $this->id       = msg_get_queue($this->ipcKey->generate());
31
        $this->stat     = msg_stat_queue($this->id);
32
    }
33
34
    /**
35
     * @param   string  $message
36
     */
37
    protected function sendMessage($message)
38
    {
39
        return msg_send($this->id, 1, $message);
40
    }
41
42
    /**
43
     * @return  string
44
     * @throws  \RuntimeException
45
     */
46
    protected function receiveMessage()
47
    {
48
        $msgtype = $message = null;
49
50
        // argument #3: specify the maximum number of bytes allowsed in one message queue.
51
        $success = msg_receive($this->id, 1, $msgtype, $this->stat['msg_qbytes'], $message);
52
        if (!$success) {
53
            throw new \RuntimeException('failed to receive message.');
54
        }
55
56
        return $message;
57
    }
58
59
    /**
60
     * @param   string  $message
61
     * @return  bool
62
     */
63
    protected function isExceedsLimit($message)
64
    {
65
        return $this->stat['msg_qbytes'] < strlen($message);
66
    }
67
68
    /**
69
     * @return  int
70
     */
71
    public function queuedCount()
72
    {
73
        return $this->queuedCount;
74
    }
75
76
    /**
77
     * @return  int
78
     */
79
    public function dequeuedCount()
80
    {
81
        return $this->dequeuedCount;
82
    }
83
84
    abstract public function enqueue($something);
85
    abstract public function dequeue();
86
87
    public function __destruct()
88
    {
89
        if ($this->ipcKey->isOwner(getmypid())) {
90
            $this->ipcKey->delete();
91
            return msg_remove_queue($this->id);
92
        }
93
    }// @codeCoverageIgnore
94
}
95