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
|
|
|
|