Passed
Push — master ( 1ebcaf...2515b7 )
by Thomas
07:17
created

UserHandle::random()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 6
rs 10
1
<?php
2
3
namespace MadWizard\WebAuthn\Credential;
4
5
use Exception;
6
use MadWizard\WebAuthn\Exception\NotAvailableException;
7
use MadWizard\WebAuthn\Exception\WebAuthnException;
8
use MadWizard\WebAuthn\Format\Base64UrlEncoding;
9
use MadWizard\WebAuthn\Format\BinaryHandle;
10
use MadWizard\WebAuthn\Format\ByteBuffer;
11
use function hash_equals;
12
use function sprintf;
13
14
class UserHandle extends BinaryHandle
15
{
16
    /**
17
     * SPEC: 4 Terminology - User Handle.
18
     */
19
    public const MAX_USER_HANDLE_BYTES = 64;
20
21 25
    protected function __construct(string $rawBytes)
22
    {
23 25
        if (\strlen($rawBytes) > self::MAX_USER_HANDLE_BYTES) {
24 1
            throw new WebAuthnException(sprintf('User handle cannot be larger than %d bytes.', self::MAX_USER_HANDLE_BYTES));
25
        }
26 24
        parent::__construct($rawBytes);
27 24
    }
28
29 2
    public static function fromString(string $base64urlString): self
30
    {
31 2
        return new self(Base64UrlEncoding::decode($base64urlString));
32
    }
33
34 2
    public static function fromBinary(string $binary): self
35
    {
36 2
        return new self($binary);
37
    }
38
39 21
    public static function fromHex(string $hex): self
40
    {
41 21
        return new self(parent::convertHex($hex));
42
    }
43
44 2
    public static function fromBuffer(ByteBuffer $buffer): self
45
    {
46 2
        return new self($buffer->getBinaryString());
47
    }
48
49
    public static function random(int $length = self::MAX_USER_HANDLE_BYTES): self
50
    {
51
        try {
52
            return new UserHandle(random_bytes($length));
53
        } catch (Exception $e) {
54
            throw new NotAvailableException('Cannot generate random bytes for user handle.', 0, $e);
55
        }
56
    }
57
58 5
    public function equals(self $other): bool
59
    {
60 5
        return hash_equals($this->raw, $other->raw);
61
    }
62
}
63