Completed
Pull Request — master (#8)
by Mr
01:31
created

APIConnector   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 2
dl 0
loc 45
ccs 9
cts 9
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A readWord() 0 6 2
A writeWord() 0 5 1
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
     * Constructor
24
     *
25
     * @param StreamInterface $stream
26
     */
27
28 17
    public function __construct(StreamInterface $stream)
29
    {
30 17
        $this->stream = $stream;
31 17
    }
32
33
    /**
34
     * Reads a WORD from the stream
35
     *
36
     * WORDs are part of SENTENCE. Each WORD has to be encoded in certain way - length of the WORD followed by WORD content.
37
     * Length of the WORD should be given as count of bytes that are going to be sent
38
     *
39
     * @return string The word content, en empty string for end of SENTENCE
40
     */
41 16
    public function readWord(): string
42
    {
43
        // Get length of next word
44 16
        $length = APILengthCoDec::decodeLength($this->stream);
45 16
        return ($length > 0) ? $this->stream->read($length) : '';
46
    }
47
48
    /**
49
     * Write word to stream
50
     *
51
     * @param   string $word
52
     * @return  int return number of written bytes
53
     */
54 18
    public function writeWord(string $word): int
55
    {
56 18
        $encodedLength = APILengthCoDec::encodeLength(strlen($word));
57 18
        return $this->stream->write($encodedLength . $word);
58
    }
59
}
60