Completed
Pull Request — master (#40)
by Mr
06:35
created

StringStream::read()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 12
cp 0
rs 9.504
c 0
b 0
f 0
cc 4
nc 4
nop 1
crap 20
1
<?php
2
3
namespace RouterOS\Streams;
4
5
use InvalidArgumentException;
6
use RouterOS\Interfaces\StreamInterface;
7
use RouterOS\Exceptions\StreamException;
8
9
/**
10
 * class StringStream
11
 *
12
 * Initialized with a string, the read method retreive it as done with fread, consuming the buffer.
13
 * When all the string has been read, exception is thrown when try to read again.
14
 *
15
 * @package RouterOS\Streams
16
 * @since   0.9
17
 */
18
class StringStream implements StreamInterface
19
{
20
    /**
21
     * @var string $buffer Stores the string to use
22
     */
23
    protected $buffer;
24
25
    /**
26
     * StringStream constructor.
27
     *
28
     * @param string $string
29
     */
30
    public function __construct(string $string)
31
    {
32
        $this->buffer = $string;
33
    }
34
35
36
    /**
37
     * @inheritDoc
38
     *
39
     * @throws \RouterOS\Exceptions\StreamException
40
     */
41
    public function read(int $length): string
42
    {
43
        $remaining = strlen($this->buffer);
44
45
        if ($length < 0) {
46
            throw new InvalidArgumentException('Cannot read a negative count of bytes from a stream');
47
        }
48
49
        if (0 === $remaining) {
50
            throw new StreamException('End of stream');
51
        }
52
53
        if ($length >= $remaining) {
54
            // returns all 
55
            $result = $this->buffer;
56
            // No more in the buffer
57
            $this->buffer = '';
58
        } else {
59
            // acquire $length characters from the buffer
60
            $result = substr($this->buffer, 0, $length);
61
            // remove $length characters from the buffer
62
            $this->buffer = substr_replace($this->buffer, '', 0, $length);
63
        }
64
65
        return $result;
66
    }
67
68
    /**
69
     * @inheritDoc
70
     *
71
     * @throws \InvalidArgumentException on invalid length
72
     */
73
    public function write(string $string, int $length = null): int
74
    {
75
        if (null === $length) {
76
            $length = strlen($string);
77
        }
78
79
        if ($length < 0) {
80
            throw new InvalidArgumentException('Cannot write a negative count of bytes');
81
        }
82
83
        return min($length, strlen($string));
84
    }
85
86
    /**
87
     * @inheritDoc
88
     */
89
    public function close(): void
90
    {
91
        $this->buffer = '';
92
    }
93
}
94