Completed
Pull Request — master (#2)
by thomas
01:43
created

HexCodec::convertHexPayloadToBinary()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
ccs 0
cts 4
cp 0
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\Trezor\Bridge\Codec\CallMessage;
6
7
use BitWasp\Trezor\Bridge\Util\StreamUtil;
8
use Psr\Http\Message\StreamInterface;
9
10
class HexCodec
11
{
12
    /**
13
     * @var StreamUtil
14
     */
15
    private $stream;
16
17 9
    public function __construct()
18
    {
19 9
        $this->stream = new StreamUtil();
20 9
    }
21
22 1
    public function parsePayload(StreamInterface $stream): array
23
    {
24 1
        if ($stream->getSize() < 12) {
25
            throw new \Exception("Malformed data (size too small)");
26
        }
27
28 1
        $stream = $this->stream->hex2bin($stream);
29
30 1
        list ($type) = array_values(unpack('n', $stream->read(2)));
31 1
        $stream->seek(2);
32
33 1
        list ($size) = array_values(unpack('N', $stream->read(4)));
34 1
        $stream->seek(6);
35
36 1
        if ($size > ($stream->getSize() - 6)) {
37
            throw new \Exception("Malformed data (sent more than size)");
38
        }
39
40 1
        return [$type, $this->stream->createStream($stream->read($size))];
41
    }
42
43 1
    public function encode(int $messageType, \Protobuf\Message $protobuf): string
44
    {
45 1
        $stream = $protobuf->toStream();
46 1
        return unpack(
47 1
            'H*',
48 1
            sprintf(
49 1
                "%s%s",
50 1
                pack('nN', $messageType, $stream->getSize()),
51 1
                $stream->getContents()
52
            )
53 1
        )[1];
54
    }
55
}
56