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

StreamUtil::hex2bin()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\Trezor\Bridge\Util;
6
7
use BitWasp\Trezor\Bridge\Exception\InvalidMessageException;
8
use GuzzleHttp\Psr7\Stream;
9
use Psr\Http\Message\StreamInterface;
10
11
class StreamUtil
12
{
13
    /**
14
     * @param string $stringToConvert
15
     * @return resource
16
     */
17 11
    public function createStream(string $stringToConvert)
18
    {
19 11
        $stream = fopen('php://memory', 'w+');
20 11
        if (!is_resource($stream)) {
21
            throw new \RuntimeException("Failed to create stream");
22
        }
23
24 11
        $wrote = fwrite($stream, $stringToConvert);
25 11
        if ($wrote !== strlen($stringToConvert)) {
26
            throw new \RuntimeException("Failed to write to stream");
27
        }
28
29 11
        rewind($stream);
30 11
        return $stream;
31
    }
32
33
    /**
34
     * @param StreamInterface $hexStream
35
     * @return StreamInterface
36
     */
37 5
    public function hex2bin(StreamInterface $hexStream): StreamInterface
38
    {
39 5
        $hex = $hexStream->getContents();
40 5
        if (!ctype_xdigit($hex)) {
41 1
            throw new InvalidMessageException("Invalid hex as input");
42
        }
43
44 4
        return new Stream($this->createStream(pack("H*", $hex)));
45
    }
46
}
47