| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
/* |
| 6 |
* The MIT License (MIT) |
| 7 |
* |
| 8 |
* Copyright (c) 2014-2021 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 Webauthn; |
| 15 |
|
| 16 |
use Assert\Assertion; |
| 17 |
use Base64Url\Base64Url; |
| 18 |
use function count; |
| 19 |
use JsonSerializable; |
| 20 |
use function Safe\json_decode; |
| 21 |
|
| 22 |
class PublicKeyCredentialDescriptor implements JsonSerializable |
| 23 |
{ |
| 24 |
public const CREDENTIAL_TYPE_PUBLIC_KEY = 'public-key'; |
| 25 |
|
| 26 |
public const AUTHENTICATOR_TRANSPORT_USB = 'usb'; |
| 27 |
public const AUTHENTICATOR_TRANSPORT_NFC = 'nfc'; |
| 28 |
public const AUTHENTICATOR_TRANSPORT_BLE = 'ble'; |
| 29 |
public const AUTHENTICATOR_TRANSPORT_INTERNAL = 'internal'; |
| 30 |
|
| 31 |
/** |
| 32 |
* @var string |
| 33 |
*/ |
| 34 |
protected $type; |
| 35 |
|
| 36 |
/** |
| 37 |
* @var string |
| 38 |
*/ |
| 39 |
protected $id; |
| 40 |
|
| 41 |
/** |
| 42 |
* @var string[] |
| 43 |
*/ |
| 44 |
protected $transports; |
| 45 |
|
| 46 |
/** |
| 47 |
* @param string[] $transports |
| 48 |
*/ |
| 49 |
public function __construct(string $type, string $id, array $transports = []) |
| 50 |
{ |
| 51 |
$this->type = $type; |
| 52 |
$this->id = $id; |
| 53 |
$this->transports = $transports; |
| 54 |
} |
| 55 |
|
| 56 |
public function getType(): string |
| 57 |
{ |
| 58 |
return $this->type; |
| 59 |
} |
| 60 |
|
| 61 |
public function getId(): string |
| 62 |
{ |
| 63 |
return $this->id; |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* @return string[] |
| 68 |
*/ |
| 69 |
public function getTransports(): array |
| 70 |
{ |
| 71 |
return $this->transports; |
| 72 |
} |
| 73 |
|
| 74 |
public static function createFromString(string $data): self |
| 75 |
{ |
| 76 |
$data = json_decode($data, true); |
| 77 |
Assertion::isArray($data, 'Invalid data'); |
| 78 |
|
| 79 |
return self::createFromArray($data); |
| 80 |
} |
| 81 |
|
| 82 |
/** |
| 83 |
* @param mixed[] $json |
| 84 |
*/ |
| 85 |
public static function createFromArray(array $json): self |
| 86 |
{ |
| 87 |
Assertion::keyExists($json, 'type', 'Invalid input. "type" is missing.'); |
| 88 |
Assertion::keyExists($json, 'id', 'Invalid input. "id" is missing.'); |
| 89 |
|
| 90 |
return new self( |
| 91 |
$json['type'], |
| 92 |
Base64Url::decode($json['id']), |
| 93 |
$json['transports'] ?? [] |
| 94 |
); |
| 95 |
} |
| 96 |
|
| 97 |
/** |
| 98 |
* @return mixed[] |
| 99 |
*/ |
| 100 |
public function jsonSerialize(): array |
| 101 |
{ |
| 102 |
$json = [ |
| 103 |
'type' => $this->type, |
| 104 |
'id' => Base64Url::encode($this->id), |
| 105 |
]; |
| 106 |
if (0 !== count($this->transports)) { |
| 107 |
$json['transports'] = $this->transports; |
| 108 |
} |
| 109 |
|
| 110 |
return $json; |
| 111 |
} |
| 112 |
} |
| 113 |
|