Passed
Pull Request — master (#2)
by thomas
01:58
created

HexCodec   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
dl 0
loc 57
c 0
b 0
f 0
ccs 28
cts 28
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A encode() 0 11 1
B parsePayload() 0 27 5
A intcmp() 0 3 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
    /**
13
     * Implement integer comparison
14
     * Returns: 0 if  $a === $b
15
     *         -1 if  $a  <  $b
16
     *         +1 if  $a  >  $b
17
     *
18
     * @param int $a
19
     * @param int $b
20
     * @return int
21
     */
22 32
    private function intcmp(int $a, int $b): int
23
    {
24 32
        return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
25
    }
26
27 39
    public function parsePayload(StreamInterface $stream): array
28
    {
29 39
        if ($stream->getSize() < 12) {
30 6
            throw new InvalidMessageException("Malformed data (size too small)");
31
        }
32
33 33
        $hex = $stream->getContents();
34 33
        if (!ctype_xdigit($hex)) {
35 1
            throw new InvalidMessageException("Invalid hex as input");
36
        }
37
38 32
        $stream = \Protobuf\Stream::fromString(pack("H*", $hex));
39
40 32
        list ($type) = array_values(unpack('n', $stream->read(2)));
41 32
        $stream->seek(2);
42
43 32
        list ($size) = array_values(unpack('N', $stream->read(4)));
44 32
        $stream->seek(6);
45
46 32
        $lCmp = $this->intcmp($stream->getSize() - 6, $size);
47 32
        if ($lCmp < 0) {
48 1
            throw new InvalidMessageException("Malformed data (not enough data)");
49 31
        } else if ($lCmp > 0) {
50 1
            throw new InvalidMessageException("Malformed data (too much data)");
51
        }
52
53 30
        return [$type, \Protobuf\Stream::wrap($stream->read($size))];
54
    }
55
56 30
    public function encode(int $messageType, \Protobuf\Message $protobuf): string
57
    {
58 30
        $stream = $protobuf->toStream();
59 30
        return unpack(
60 30
            'H*',
61 30
            sprintf(
62 30
                "%s%s",
63 30
                pack('nN', $messageType, $stream->getSize()),
64 30
                $stream->getContents()
65
            )
66 30
        )[1];
67
    }
68
}
69