Passed
Pull Request — master (#6)
by thomas
02:18
created

HexCodec::encode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 2
crap 1
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 33
    private function hex2bin(StreamInterface $stream): \Protobuf\Stream
28
    {
29 33
        $hex = $stream->getContents();
30 33
        if (!ctype_xdigit($hex)) {
31 1
            throw new InvalidMessageException("Invalid hex as input");
32
        }
33
34 32
        return \Protobuf\Stream::fromString(pack("H*", $hex));
35
    }
36
37 39
    public function parsePayload(StreamInterface $stream): array
38
    {
39 39
        if ($stream->getSize() < 12) {
40 6
            throw new InvalidMessageException("Malformed data (size too small)");
41
        }
42
43 33
        $stream = $this->hex2bin($stream);
44
        // relies on php returning the variables in order defined in unpack string
45 32
        list ($type, $size) = array_values(unpack('n1type/N1size', $stream->read(6)));
46 32
        $stream->seek(6);
47
48 32
        $lCmp = $this->intcmp($stream->getSize() - 6, $size);
49 32
        if ($lCmp < 0) {
50 1
            throw new InvalidMessageException("Malformed data (not enough data)");
51 31
        } else if ($lCmp > 0) {
52 1
            throw new InvalidMessageException("Malformed data (too much data)");
53
        }
54
55 30
        return [$type, \Protobuf\Stream::wrap($stream->read($size))];
56
    }
57
58 30
    public function encode(int $messageType, \Protobuf\Message $protobuf): string
59
    {
60 30
        $stream = $protobuf->toStream();
61 30
        return unpack(
62 30
            'H*',
63 30
            sprintf(
64 30
                "%s%s",
65 30
                pack('nN', $messageType, $stream->getSize()),
66 30
                $stream->getContents()
67
            )
68 30
        )[1];
69
    }
70
}
71