MojangAccountFactory::makeFromApiResponse()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 28
rs 9.4555
c 0
b 0
f 0
cc 5
nc 6
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Minepic\Minecraft;
6
7
class MojangAccountFactory
8
{
9
    /**
10
     * @throws \JsonException
11
     */
12
    public static function makeFromApiResponse(array $response): MojangAccount
13
    {
14
        $uuid = $response['id'];
15
        $username = $response['name'];
16
        $skin = '';
17
        $cape = '';
18
19
        if (!\array_key_exists('properties', $response)) {
20
            return new MojangAccount($uuid, $username, $skin, $cape);
21
        }
22
23
        $textures = array_filter($response['properties'], static function (array $entry) {
24
            return $entry['name'] === 'textures';
25
        });
26
27
        if (!empty($textures)) {
28
            $textureData = json_decode((string) base64_decode($textures[0]['value'], true), associative: true, flags: \JSON_THROW_ON_ERROR);
29
30
            if (isset($textureData['textures']['SKIN']['url'])) {
31
                $skin = self::extractTextureIdFromUrl($textureData['textures']['SKIN']['url']);
32
            }
33
34
            if (isset($textureData['textures']['CAPE']['url'])) {
35
                $cape = self::extractTextureIdFromUrl($textureData['textures']['CAPE']['url']);
36
            }
37
        }
38
39
        return new MojangAccount($uuid, $username, $skin, $cape);
40
    }
41
42
    /**
43
     * Extract texture (skin/cape) ids from URL.
44
     */
45
    private static function extractTextureIdFromUrl(string $url): string
46
    {
47
        preg_match('#'.env('MINECRAFT_TEXTURE_URL').'(.*)$#', $url, $matches);
48
49
        return $matches[1] ?? '';
50
    }
51
}
52