Passed
Pull Request — master (#2)
by thomas
02:16
created

StreamUtil   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 85.71%

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 34
ccs 12
cts 14
cp 0.8571
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 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 10
    public function createStream(string $stringToConvert)
18
    {
19 10
        $stream = fopen('php://memory', 'w+');
20 10
        if (!is_resource($stream)) {
21
            throw new \RuntimeException("Failed to create stream");
22
        }
23
24 10
        $wrote = fwrite($stream, $stringToConvert);
25 10
        if ($wrote !== strlen($stringToConvert)) {
26
            throw new \RuntimeException("Failed to write to stream");
27
        }
28
29 10
        rewind($stream);
30 10
        return $stream;
31
    }
32
33
    /**
34
     * @param StreamInterface $hexStream
35
     * @return StreamInterface
36
     */
37 4
    public function hex2bin(StreamInterface $hexStream): StreamInterface
38
    {
39 4
        $hex = $hexStream->getContents();
40 4
        if (!ctype_xdigit($hex)) {
41 1
            throw new InvalidMessageException("Invalid hex as input");
42
        }
43
44 3
        return new Stream($this->createStream(pack("H*", $hex)));
45
    }
46
}
47