MojangClient   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 17
eloc 49
dl 0
loc 159
rs 10
c 2
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A sendRequest() 0 12 3
A sendApiRequest() 0 23 4
A sendUsernameInfoRequest() 0 9 2
A handleThrowable() 0 4 1
A getCacheKey() 0 3 1
A getUuidInfo() 0 9 2
A getSkin() 0 9 2
A __construct() 0 6 1
A handleGuzzleBadResponseException() 0 9 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Minepic\Minecraft;
6
7
use GuzzleHttp\Client as HttpClient;
8
use GuzzleHttp\Exception\BadResponseException;
9
use Illuminate\Support\Facades\Log;
10
use Minepic\Minecraft\Exceptions\UserNotFoundException;
11
use Psr\Http\Message\ResponseInterface;
12
13
class MojangClient
14
{
15
    /**
16
     * API response TTL.
17
     */
18
    private const CACHE_TTL = 120;
19
    /**
20
     * User Agent used for requests.
21
     */
22
    private const USER_AGENT = 'Minepic/2.0 (minepic.org)';
23
24
    /**
25
     * HTTP Client for requests.
26
     */
27
    private HttpClient $httpClient;
28
29
    /**
30
     * MojangClient constructor.
31
     */
32
    public function __construct()
33
    {
34
        $this->httpClient = new HttpClient(
35
            [
36
                'headers' => [
37
                    'User-Agent' => self::USER_AGENT,
38
                ],
39
            ]
40
        );
41
    }
42
43
    /**
44
     * Account info from username.
45
     *
46
     * @throws \Throwable
47
     */
48
    public function sendUsernameInfoRequest(string $username): MojangAccount
49
    {
50
        $response = $this->sendApiRequest('GET', env('MINECRAFT_PROFILE_URL').$username);
51
52
        if ($response !== null) {
53
            return new MojangAccount($response['id'], $response['name']);
54
        }
55
56
        throw new UserNotFoundException("Unknown user {$username}");
57
    }
58
59
    /**
60
     * Account info from UUID.
61
     *
62
     * @param string $uuid User UUID
63
     *
64
     * @throws \Throwable
65
     */
66
    public function getUuidInfo(string $uuid): MojangAccount
67
    {
68
        $response = $this->sendApiRequest('GET', env('MINECRAFT_SESSION_URL').$uuid);
69
70
        if ($response === null) {
71
            throw new \Exception('Cannot create data account');
72
        }
73
74
        return MojangAccountFactory::makeFromApiResponse($response);
75
    }
76
77
    /**
78
     * Get Skin.
79
     *
80
     * @param string $skin Skin uuid
81
     *
82
     * @throws \Exception|\Throwable
83
     */
84
    public function getSkin(string $skin): string
85
    {
86
        $response = $this->sendRequest('GET', env('MINECRAFT_TEXTURE_URL').$skin);
87
88
        if ($response->getHeader('content-type')[0] === 'image/png') {
89
            return $response->getBody()->getContents();
90
        }
91
92
        throw new \Exception('Invalid Response content type: '.$response->getHeader('content-type')[0]);
93
    }
94
95
    private function handleGuzzleBadResponseException(
96
        BadResponseException $badResponseException
97
    ): void {
98
        Log::error(
99
            'Error from Minecraft API',
100
            [
101
                'status_code' => $badResponseException->getResponse()->getStatusCode(),
102
                'content_type' => $badResponseException->getResponse()->getHeader('content-type')[0] ?? '',
103
                'content' => $badResponseException->getResponse()->getBody()->getContents(),
104
            ]
105
        );
106
    }
107
108
    private function handleThrowable(\Throwable $exception): void
109
    {
110
        Log::error($exception->getFile().':'.$exception->getLine().' - '.$exception->getMessage());
111
        Log::error($exception->getTraceAsString());
112
    }
113
114
    private function getCacheKey(string $method, string $url): string
115
    {
116
        return 'minecraft_api_response_'.md5($method.'_'.$url);
117
    }
118
119
    /**
120
     * Send new request.
121
     *
122
     * @param string $method HTTP Verb
123
     * @param string $url    API Endpoint
124
     *
125
     * @throws \Throwable
126
     *
127
     * @return array
128
     */
129
    private function sendApiRequest(string $method, string $url): ?array
130
    {
131
        try {
132
            return \Cache::remember($this->getCacheKey($method, $url), self::CACHE_TTL, function () use ($method, $url) {
133
                $response = $this->httpClient->request($method, $url);
134
                // No Content
135
                if ($response->getStatusCode() === 204) {
136
                    return null;
137
                }
138
139
                $responseContents = $response->getBody()->getContents();
140
                Log::debug('Minecraft API Response: '.$responseContents, ['method' => $method, 'url' => $url]);
141
142
                return json_decode($responseContents, associative: true, flags: \JSON_THROW_ON_ERROR);
143
            });
144
        } catch (BadResponseException $exception) {
145
            $this->handleGuzzleBadResponseException($exception);
146
147
            throw $exception;
148
        } catch (\Throwable $exception) {
149
            $this->handleThrowable($exception);
150
151
            throw $exception;
152
        }
153
    }
154
155
    /**
156
     * Generic request.
157
     *
158
     * @throws \Throwable
159
     */
160
    private function sendRequest(string $method, string $url): ResponseInterface
161
    {
162
        try {
163
            return $this->httpClient->request($method, $url);
164
        } catch (BadResponseException $exception) {
165
            $this->handleGuzzleBadResponseException($exception);
166
167
            throw $exception;
168
        } catch (\Throwable $exception) {
169
            $this->handleThrowable($exception);
170
171
            throw $exception;
172
        }
173
    }
174
}
175