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

UserHandle::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 3
rs 10
c 1
b 0
f 0
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