Completed
Pull Request — master (#40)
by Mr
05:34
created

APIConnector::close()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace RouterOS;
4
5
use RouterOS\Interfaces\StreamInterface;
6
7
/**
8
 * Class APIConnector
9
 *
10
 * Implement middle level dialog with router by masking word dialog implementation to client class
11
 *
12
 * @package RouterOS
13
 * @since   0.9
14
 */
15
class APIConnector
16
{
17
    /**
18
     * @var StreamInterface $stream The stream used to communicate with the router
19
     */
20
    protected $stream;
21
22
    /**
23
     * APIConnector constructor.
24
     *
25
     * @param \RouterOS\Interfaces\StreamInterface $stream
26
     */
27 24
    public function __construct(StreamInterface $stream)
28
    {
29 24
        $this->stream = $stream;
30 24
    }
31
32
    /**
33
     * Close stream connection
34
     *
35
     * @return void
36
     */
37
    public function close(): void
38
    {
39
        $this->stream->close();
40
    }
41
42
    /**
43
     * Reads a WORD from the stream
44
     *
45
     * WORDs are part of SENTENCE. Each WORD has to be encoded in certain way - length of the WORD followed by WORD content.
46
     * Length of the WORD should be given as count of bytes that are going to be sent
47
     *
48
     * @return string The word content, en empty string for end of SENTENCE
49
     */
50 23
    public function readWord(): string
51
    {
52
        // Get length of next word
53 23
        $length = APILengthCoDec::decodeLength($this->stream);
54 23
        return ($length > 0) ? $this->stream->read($length) : '';
55
    }
56
57
    /**
58
     * Write word to stream
59
     *
60
     * @param string $word
61
     *
62
     * @return int return number of written bytes
63
     */
64 25
    public function writeWord(string $word): int
65
    {
66 25
        $encodedLength = APILengthCoDec::encodeLength(strlen($word));
67 25
        return $this->stream->write($encodedLength . $word);
68
    }
69
}
70