Completed
Push — master ( 32c328...253a84 )
by Valentin
15s queued 11s
created

WriteHistory::log()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Pheanstalk\Socket;
4
5
/**
6
 * A limited history of recent socket write length/success.
7
 *
8
 * Facilitates retrying zero-length writes a limited number of times,
9
 * avoiding infinite loops.
10
 *
11
 * Based on a patch from https://github.com/leprechaun
12
 * https://github.com/pda/pheanstalk/pull/24
13
 *
14
 * A bitfield could be used instead of an array for efficiency.
15
 *
16
 * @author  Paul Annesley
17
 * @package Pheanstalk
18
 * @license http://www.opensource.org/licenses/mit-license.php
19
 */
20
class WriteHistory
21
{
22
    private $_limit;
23
    private $_data = [];
24
25
    /**
26
     * @param int $limit
27
     */
28 26
    public function __construct($limit)
29
    {
30 26
        $this->_limit = $limit;
31
    }
32
33
    /**
34
     * Whether the history has reached its limit of entries.
35
     */
36 25
    public function isFull()
37
    {
38 25
        return count($this->_data) >= $this->_limit;
39
    }
40
41 1
    public function hasWrites()
42
    {
43 1
        return (bool) array_sum($this->_data);
44
    }
45
46 23
    public function isFullWithNoWrites()
47
    {
48 23
        return $this->isFull() && !$this->hasWrites();
49
    }
50
51
    /**
52
     * Logs the return value from a write call.
53
     * Returns the input value.
54
     */
55 23
    public function log($write)
56
    {
57 23
        if ($this->isFull()) {
58 1
            array_shift($this->_data);
59
        }
60
61 23
        $this->_data[] = (int) $write;
62
63 23
        return $write;
64
    }
65
}
66