SignatureRequest::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2018 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace U2FAuthentication\Fido;
15
16
use Assert\Assertion;
17
use Base64Url\Base64Url;
18
19
class SignatureRequest implements \JsonSerializable
20
{
21
    /**
22
     * @var string
23
     */
24
    private $applicationId;
25
26
    /**
27
     * @var string
28
     */
29
    private $challenge;
30
31
    /**
32
     * @var RegisteredKey[]
33
     */
34
    private $registeredKeys = [];
35
36
    /**
37
     * @param RegisteredKey[] $registeredKeys
38
     */
39
    public function __construct(string $applicationId, array $registeredKeys)
40
    {
41
        $this->applicationId = $applicationId;
42
        foreach ($registeredKeys as $registeredKey) {
43
            Assertion::isInstanceOf($registeredKey, RegisteredKey::class, 'Invalid registered keys list.');
44
            $this->registeredKeys[Base64Url::encode((string) $registeredKey->getKeyHandler())] = $registeredKey;
45
        }
46
        $this->challenge = random_bytes(32);
47
    }
48
49
    public function addRegisteredKey(RegisteredKey $registeredKey): void
50
    {
51
        $this->registeredKeys[Base64Url::encode((string) $registeredKey->getKeyHandler())] = $registeredKey;
52
    }
53
54
    public function hasRegisteredKey(KeyHandler $keyHandle): bool
55
    {
56
        return array_key_exists(Base64Url::encode($keyHandle->getValue()), $this->registeredKeys);
57
    }
58
59
    public function getRegisteredKey(KeyHandler $keyHandle): RegisteredKey
60
    {
61
        Assertion::true($this->hasRegisteredKey($keyHandle), 'Unsupported key handle.');
62
63
        return $this->registeredKeys[Base64Url::encode($keyHandle->getValue())];
64
    }
65
66
    public function getApplicationId(): string
67
    {
68
        return $this->applicationId;
69
    }
70
71
    public function getChallenge(): string
72
    {
73
        return $this->challenge;
74
    }
75
76
    /**
77
     * @return RegisteredKey[]
78
     */
79
    public function getRegisteredKeys(): array
80
    {
81
        return $this->registeredKeys;
82
    }
83
84
    public function jsonSerialize(): array
85
    {
86
        return [
87
            'appId' => $this->applicationId,
88
            'challenge' => Base64Url::encode($this->challenge),
89
            'registeredKeys' => array_values($this->registeredKeys),
90
        ];
91
    }
92
}
93