Lines 100.00% 31 / 31
Functions and Methods 100.00% 2 / 2
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ServerListClient 100.00% 31 / 31 100.00% 2 / 2 4 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 fetch 100.00% 30 / 30 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Client\Api\Server;
6
7use Lorekeeper\Server\Server;
8use Psl\Network\Address;
9use Psl\Type;
10use Psl\Type\Exception\CoercionException;
11
12final readonly class ServerListClient
13{
14    /** @param non-empty-string $url */
15    public function __construct(
16        private string $url = 'https://game.aq.com/game/api/data/servers',
17    ) {}
18
19    /**
20     * @throws ServerListUnavailableException
21     *
22     * @return list<Server>
23     */
24    public function fetch(): array
25    {
26        $curl = curl_init($this->url);
27        curl_setopt_array($curl, [
28            CURLOPT_RETURNTRANSFER => true,
29            CURLOPT_FOLLOWLOCATION => true,
30            CURLOPT_TIMEOUT => 10,
31            CURLOPT_CONNECTTIMEOUT => 5,
32            CURLOPT_USERAGENT => 'Mozilla/5.0',
33        ]);
34
35        $response = curl_exec($curl);
36        if (!is_string($response)) {
37            throw new ServerListUnavailableException('Could not reach the server list API: ' . curl_error($curl));
38        }
39
40        try {
41            $servers = Type\json_decoded(Type\vec(Type\shape([
42                'sName' => Type\non_empty_string(),
43                'sIP' => Type\non_empty_string(),
44                'iPort' => Type\int_range(min: 1, max: 65_535),
45                'bOnline' => Type\int(),
46                'bUpg' => Type\int(),
47            ], allowUnknownFields: true)))
48                ->coerce($response);
49        } catch (CoercionException $exception) {
50            throw new ServerListUnavailableException('Unexpected server list response.', previous: $exception);
51        }
52
53        return 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            $servers,
61        );
62    }
63}