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

StreamUtil   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 78.56%

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 34
ccs 11
cts 14
cp 0.7856
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A createStream() 0 14 3
A hex2bin() 0 8 2
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