Lines
100.00%
29 / 29
Functions and Methods
100.00%
2 / 2
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| LoginResult | 100.00% | 29 / 29 | 100.00% | 2 / 2 | 4 | 100.00% | 1 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| fromJson | 100.00% | 28 / 28 | 100.00% | 1 / 1 | 3 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Lorekeeper\Client\Api\Login; | |
| 6 | ||
| 7 | use Lorekeeper\Server\Server; | |
| 8 | use Psl\Network\Address; | |
| 9 | use Psl\Type; | |
| 10 | use Psl\Type\Exception\CoercionException; | |
| 11 | use SensitiveParameter; | |
| 12 | ||
| 13 | final readonly class LoginResult | |
| 14 | { | |
| 15 | /** | |
| 16 | * @param non-empty-string $token | |
| 17 | * @param list<Server> $servers | |
| 18 | */ | |
| 19 | public function __construct( | |
| 20 | #[SensitiveParameter] | |
| 21 | public string $token, | |
| 22 | public array $servers, | |
| 23 | ) {} | |
| 24 | ||
| 25 | /** @throws LoginFailedException */ | |
| 26 | public static function fromJson(#[SensitiveParameter] string $json): self | |
| 27 | { | |
| 28 | $type = Type\json_decoded(Type\shape([ | |
| 29 | 'login' => Type\optional(Type\shape([ | |
| 30 | 'sToken' => Type\non_empty_string(), | |
| 31 | ], allowUnknownFields: true)), | |
| 32 | 'sMsg' => Type\optional(Type\string()), | |
| 33 | 'servers' => Type\optional(Type\vec(Type\shape([ | |
| 34 | 'sName' => Type\non_empty_string(), | |
| 35 | 'sIP' => Type\non_empty_string(), | |
| 36 | 'iPort' => Type\int_range(min: 1, max: 65_535), | |
| 37 | 'bOnline' => Type\int(), | |
| 38 | 'bUpg' => Type\int(), | |
| 39 | ], allowUnknownFields: true))), | |
| 40 | ], allowUnknownFields: true)); | |
| 41 | ||
| 42 | try { | |
| 43 | $response = $type->coerce($json); | |
| 44 | } catch (CoercionException $exception) { | |
| 45 | throw new LoginFailedException('Unexpected login response.', previous: $exception); | |
| 46 | } | |
| 47 | ||
| 48 | $login = $response['login'] ?? null; | |
| 49 | if ($login === null) { | |
| 50 | throw new LoginFailedException(strip_tags($response['sMsg'] ?? 'Login failed.')); | |
| 51 | } | |
| 52 | ||
| 53 | return new self($login['sToken'], array_map( | |
| 54 | static fn(array $server): Server => new Server( | |
| 55 | $server['sName'], | |
| 56 | Address::tcp($server['sIP'], $server['iPort']), | |
| 57 | $server['bOnline'] === 1, | |
| 58 | $server['bUpg'] === 1, | |
| 59 | ), | |
| 60 | $response['servers'] ?? [], | |
| 61 | )); | |
| 62 | } | |
| 63 | } |