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

StreamUtil::createStream()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0987

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 7
cts 9
cp 0.7778
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
crap 3.0987
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