BinaryHandle::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace MadWizard\WebAuthn\Format;
4
5
use InvalidArgumentException;
6
use Serializable;
7
use function bin2hex;
8
use function hex2bin;
9
10
abstract class BinaryHandle implements Serializable
11
{
12
    use SerializableTrait;
13
14
    /**
15
     * @var string
16
     */
17
    protected $raw;
18
19 29
    protected function __construct(string $rawBytes)
20
    {
21 29
        $this->raw = $rawBytes;
22 29
    }
23
24 11
    public function toString(): string
25
    {
26 11
        return Base64UrlEncoding::encode($this->raw);
27
    }
28
29 8
    public function toBinary(): string
30
    {
31 8
        return $this->raw;
32
    }
33
34 10
    public function toHex(): string
35
    {
36 10
        return bin2hex($this->raw);
37
    }
38
39 12
    public function toBuffer(): ByteBuffer
40
    {
41 12
        return new ByteBuffer($this->raw);
42
    }
43
44 25
    protected static function convertHex(string $hex): string
45
    {
46 25
        $bin = @hex2bin($hex);
47 25
        if ($bin === false) {
48 1
            throw new InvalidArgumentException('Invalid hex string');
49
        }
50 24
        return $bin;
51
    }
52
53
    public function __serialize(): array
54
    {
55
        return [
56
            'raw' => $this->raw,
57
        ];
58
    }
59
60
    public function __unserialize(array $data): void
61
    {
62
        $this->raw = $data['raw'];
63
    }
64
}
65