|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Knik\Binn\Decoder\Containers; |
|
4
|
|
|
|
|
5
|
|
|
use Knik\Binn\Binn; |
|
6
|
|
|
use Knik\Binn\Contracts\BinnValueDecoder; |
|
7
|
|
|
use Knik\Binn\Decoder\Decoder; |
|
8
|
|
|
use Knik\Binn\Decoder\DecoderCollection; |
|
9
|
|
|
use Knik\Binn\Decoder\Unpacker; |
|
10
|
|
|
|
|
11
|
|
|
class BinnObjectDecoder extends Decoder implements BinnValueDecoder |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var DecoderCollection */ |
|
14
|
|
|
private $decoders; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct(DecoderCollection $decoders) |
|
17
|
|
|
{ |
|
18
|
|
|
$this->decoders = $decoders; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function decode(string $bytes) |
|
22
|
|
|
{ |
|
23
|
|
|
$readPosition = 1; |
|
24
|
|
|
$totalSize = Unpacker::unpackSize8($bytes[$readPosition]); |
|
25
|
|
|
|
|
26
|
|
|
if ($totalSize > Binn::BINN_MAX_ONE_BYTE_SIZE) { |
|
27
|
|
|
$totalSize = Unpacker::unpackSize32(substr($bytes, $readPosition, 4)); |
|
28
|
|
|
$readPosition += 4; |
|
29
|
|
|
} else { |
|
30
|
|
|
$readPosition++; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
$totalItems = Unpacker::unpackSize8($bytes[$readPosition]); |
|
34
|
|
|
|
|
35
|
|
|
if ($totalItems > Binn::BINN_MAX_ONE_BYTE_SIZE) { |
|
36
|
|
|
$totalItems = Unpacker::unpackSize32(substr($bytes, $readPosition, 4)); |
|
37
|
|
|
$readPosition += 4; |
|
38
|
|
|
} else { |
|
39
|
|
|
$readPosition++; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$readedItems = 0; |
|
43
|
|
|
|
|
44
|
|
|
$result = []; |
|
45
|
|
|
|
|
46
|
|
|
while ($readedItems < $totalItems && $readPosition < $totalSize) { |
|
47
|
|
|
$keySize = Unpacker::unpackSize8($bytes[$readPosition]); |
|
48
|
|
|
$readPosition++; |
|
49
|
|
|
$keyValue = Unpacker::unpackString(substr($bytes, $readPosition, $keySize)); |
|
50
|
|
|
$readPosition += $keySize; |
|
51
|
|
|
|
|
52
|
|
|
$readSize = $this->readSizeWithType(substr($bytes, $readPosition, 4)); |
|
53
|
|
|
$innerStorage = substr($bytes, $readPosition, $readSize); |
|
54
|
|
|
|
|
55
|
|
|
/** @var BinnValueDecoder $decoder */ |
|
56
|
|
|
foreach ($this->decoders->getAll() as $decoder) { |
|
57
|
|
|
if ($decoder->supportsDecoding($innerStorage)) { |
|
58
|
|
|
$result[$keyValue] = $decoder->decode($innerStorage); |
|
59
|
|
|
break; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
$readPosition += $readSize; |
|
64
|
|
|
$readedItems++; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
return $result; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
public function supportsDecoding(string $bytes): bool |
|
71
|
|
|
{ |
|
72
|
|
|
$type = $this->detectType($bytes); |
|
73
|
|
|
|
|
74
|
|
|
return $type === Binn::BINN_OBJECT; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|