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