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

HexCodec::stringToStream()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
ccs 0
cts 9
cp 0
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
crap 12

1 Method

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