Completed
Pull Request — master (#2)
by thomas
01:43
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 GuzzleHttp\Psr7\Stream;
8
use Psr\Http\Message\StreamInterface;
9
10
class StreamUtil
11
{
12
    /**
13
     * @param string $stringToConvert
14
     * @return resource
15
     */
16 1
    public function createStream(string $stringToConvert)
17
    {
18 1
        $stream = fopen('php://memory', 'w+');
19 1
        if (!is_resource($stream)) {
20
            throw new \RuntimeException("Failed to create stream");
21
        }
22
23 1
        $wrote = fwrite($stream, $stringToConvert);
24 1
        if ($wrote !== strlen($stringToConvert)) {
25
            throw new \RuntimeException("Failed to write to stream");
26
        }
27
28 1
        rewind($stream);
29 1
        return $stream;
30
    }
31
32
    /**
33
     * @param StreamInterface $hexStream
34
     * @return StreamInterface
35
     */
36 1
    public function hex2bin(StreamInterface $hexStream): StreamInterface
37
    {
38 1
        $hex = $hexStream->getContents();
39 1
        if (!ctype_xdigit($hex)) {
40
            throw new \RuntimeException("Invalid hex as input");
41
        }
42
43 1
        return new Stream($this->createStream(pack("H*", $hex)));
44
    }
45
}
46