Completed
Push — master ( 8c1d4f...b44e39 )
by Chris
02:46 queued 12s
created

PacketDecoder::getMessageDecoder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace DaveRandom\LibLifxLan\Decoding;
4
5
use DaveRandom\LibLifxLan\Decoding\Exceptions\DecodingException;
6
use DaveRandom\LibLifxLan\Decoding\Exceptions\InsufficientDataException;
7
use DaveRandom\LibLifxLan\Header\Header;
8
use DaveRandom\LibLifxLan\Packet;
9
10
final class PacketDecoder
11
{
12
    private const HEADER_OFFSET = 0;
13
    private const MESSAGE_OFFSET = Header::WIRE_SIZE;
14
15
    private $headerDecoder;
16
    private $messageDecoder;
17
18 8
    public function __construct(HeaderDecoder $headerDecoder = null, MessageDecoder $messageDecoder = null)
19
    {
20 8
        $this->headerDecoder = $headerDecoder ?? new HeaderDecoder;
21 8
        $this->messageDecoder = $messageDecoder ?? new MessageDecoder;
22
    }
23
24 2
    public function getHeaderDecoder(): HeaderDecoder
25
    {
26 2
        return $this->headerDecoder;
27
    }
28
29 2
    public function getMessageDecoder(): MessageDecoder
30
    {
31 2
        return $this->messageDecoder;
32
    }
33
34
    /**
35
     * @param string $buffer
36
     * @param int $offset
37
     * @param int|null $length
38
     * @return Packet
39
     * @throws DecodingException
40
     * @throws InsufficientDataException
41
     */
42 4
    public function decodePacket(string $buffer, int $offset = 0, int $length = null): Packet
43
    {
44 4
        $dataLength = $length ?? (\strlen($buffer) - $offset);
45
46 4
        if ($dataLength < Header::WIRE_SIZE) {
47
            throw new InsufficientDataException(
48
                "Data length {$dataLength} less than minimum packet size " . Header::WIRE_SIZE
49
            );
50
        }
51
52 4
        $statedLength = \unpack('vlength', $buffer, $offset)['length'];
53
54 4
        if ($statedLength !== $dataLength) {
55 2
            throw new InsufficientDataException(
56 2
                "Packet length is stated to be {$statedLength} bytes, buffer is {$dataLength} bytes"
57
            );
58
        }
59
60 2
        $header = $this->headerDecoder->decodeHeader($buffer, $offset + self::HEADER_OFFSET);
61 2
        $payload = $this->messageDecoder->decodeMessage(
62 2
            $header->getProtocolHeader()->getType(),
63 2
            $buffer,
64 2
            $offset + self::MESSAGE_OFFSET,
65 2
            $dataLength - Header::WIRE_SIZE
66
        );
67
68 2
        return new Packet($header, $payload);
69
    }
70
}
71