Passed
Push — master ( 3266fb...94512e )
by Thomas
03:56 queued 01:13
created

UserHandle   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 80.95%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 51
ccs 17
cts 21
cp 0.8095
rs 10
wmc 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A fromHex() 0 3 1
A random() 0 6 2
A fromString() 0 3 1
A fromBinary() 0 3 1
A equals() 0 3 1
A fromBuffer() 0 3 1
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 30
    protected function __construct(string $rawBytes)
22
    {
23 30
        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 29
        if ($rawBytes === '') {
27
            // https://www.w3.org/TR/webauthn-2/#dom-publickeycredentialuserentity-id
28 5
            throw new WebAuthnException('User handle must not be empty');
29
        }
30 24
        parent::__construct($rawBytes);
31 24
    }
32
33 3
    public static function fromString(string $base64urlString): self
34
    {
35 3
        return new self(Base64UrlEncoding::decode($base64urlString));
36
    }
37
38 3
    public static function fromBinary(string $binary): self
39
    {
40 3
        return new self($binary);
41
    }
42
43 22
    public static function fromHex(string $hex): self
44
    {
45 22
        return new self(parent::convertHex($hex));
46
    }
47
48 3
    public static function fromBuffer(ByteBuffer $buffer): self
49
    {
50 3
        return new self($buffer->getBinaryString());
51
    }
52
53
    public static function random(int $length = self::MAX_USER_HANDLE_BYTES): self
54
    {
55
        try {
56
            return new UserHandle(random_bytes($length));
57
        } catch (Exception $e) {
58
            throw new NotAvailableException('Cannot generate random bytes for user handle.', 0, $e);
59
        }
60
    }
61
62 5
    public function equals(self $other): bool
63
    {
64 5
        return hash_equals($this->raw, $other->raw);
65
    }
66
}
67