Failed Conditions
Push — master ( ba8c0d...a9ded0 )
by thomas
04:50
created

HexCodec::intcmp()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 3
eloc 1
nc 4
nop 2
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\Trezor\Bridge\Codec\CallMessage;
6
7
use BitWasp\Trezor\Bridge\Exception\InvalidMessageException;
8
use Psr\Http\Message\StreamInterface;
9
10
class HexCodec
11
{
12 2
    private function intcmp(int $a, int $b): int
13
    {
14 2
        return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
15
    }
16
17 2
    private function hex2bin(StreamInterface $stream): \Protobuf\Stream
18
    {
19 2
        $hex = $stream->getContents();
20 2
        if (!ctype_xdigit($hex)) {
21
            throw new InvalidMessageException("Invalid hex as input");
22
        }
23
24 2
        return \Protobuf\Stream::fromString(pack("H*", $hex));
25
    }
26
27 2
    public function parsePayload(StreamInterface $stream): array
28
    {
29 2
        if ($stream->getSize() < 12) {
30
            throw new InvalidMessageException("Malformed data (size too small)");
31
        }
32
33 2
        $stream = $this->hex2bin($stream);
34
35
        // relies on php returning the variables in order defined in unpack string
36 2
        list ($type, $size) = array_values(unpack('n1type/N1size', $stream->read(6)));
37 2
        $stream->seek(6);
38
39 2
        $lCmp = $this->intcmp($stream->getSize() - 6, $size);
40 2
        if ($lCmp < 0) {
41
            throw new InvalidMessageException("Malformed data (not enough data)");
42 2
        } else if ($lCmp > 0) {
43
            throw new InvalidMessageException("Malformed data (too much data)");
44
        }
45
46 2
        return [$type, \Protobuf\Stream::wrap($stream->read($size))];
47
    }
48
49 2
    public function encode(int $messageType, \Protobuf\Message $protobuf): string
50
    {
51 2
        $stream = $protobuf->toStream();
52 2
        return unpack('H*', pack('nN', $messageType, $stream->getSize()) . $stream->getContents())[1];
53
    }
54
}
55