1<?php 2 3declare(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 14namespace Webauthn; 15 16use Assert\Assertion; 17use function Safe\base64_decode; 18use function Safe\json_decode; 19 20class PublicKeyCredentialUserEntity extends PublicKeyCredentialEntity 21{ 22 /** 23 * @var string 24 */ 25 protected $id; 26 27 /** 28 * @var string 29 */ 30 protected $displayName; 31 32 public function __construct(string $name, string $id, string $displayName, ?string $icon = null) 33 { 34 parent::__construct($name, $icon); 35 Assertion::maxLength($id, 64, 'User ID max length is 64 bytes', 'id', '8bit'); 36 $this->id = $id; 37 $this->displayName = $displayName; 38 } 39 40 public function getId(): string 41 { 42 return $this->id; 43 } 44 45 public function getDisplayName(): string 46 { 47 return $this->displayName; 48 } 49 50 public static function createFromString(string $data): self 51 { 52 $data = json_decode($data, true); 53 Assertion::isArray($data, 'Invalid data'); 54 55 return self::createFromArray($data); 56 } 57 58 /** 59 * @param mixed[] $json 60 */ 61 public static function createFromArray(array $json): self 62 { 63 Assertion::keyExists($json, 'name', 'Invalid input. "name" is missing.'); 64 Assertion::keyExists($json, 'id', 'Invalid input. "id" is missing.'); 65 Assertion::keyExists($json, 'displayName', 'Invalid input. "displayName" is missing.'); 66 $id = base64_decode($json['id'], true); 67 68 return new self( 69 $json['name'], 70 $id, 71 $json['displayName'], 72 $json['icon'] ?? null 73 ); 74 } 75 76 /** 77 * @return mixed[] 78 */ 79 public function jsonSerialize(): array 80 { 81 $json = parent::jsonSerialize(); 82 $json['id'] = base64_encode($this->id); 83 $json['displayName'] = $this->displayName; 84 85 return $json; 86 } 87} 88