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

HexCodec::__construct()   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
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
crap 1
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