Passed
Push — master ( 165425...e22481 )
by Mattia
04:28
created

MojangAccountFactory::makeFromApiResponse()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 26
rs 9.4888
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
/**
8
 * Class MojangAccountFactory.
9
 */
10
class MojangAccountFactory
11
{
12
    /**
13
     * Extract texture (skin/cape) ids from URL.
14
     *
15
     * @param string $url
16
     *
17
     * @return string
18
     */
19
    private static function extractTextureIdFromUrl(string $url): string
20
    {
21
        \preg_match('#'.env('MINECRAFT_TEXTURE_URL').'(.*)$#', $url, $matches);
22
23
        return $matches[1] ?? '';
24
    }
25
26
    /**
27
     * @param array $response
28
     *
29
     * @throws \JsonException
30
     *
31
     * @return MojangAccount
32
     */
33
    public static function makeFromApiResponse(array $response): MojangAccount
34
    {
35
        $uuid = $response['id'];
36
        $username = $response['name'];
37
        $skin = '';
38
        $cape = '';
39
40
        if (\array_key_exists('properties', $response)) {
41
            $textures = \array_filter($response['properties'], static function ($entry) {
42
                return $entry['name'] === 'textures';
43
            });
44
45
            if (!empty($textures)) {
46
                $textureData = \json_decode(\base64_decode($textures[0]['value'], true), true, 512, JSON_THROW_ON_ERROR);
47
48
                if (isset($textureData['textures']['SKIN']['url'])) {
49
                    $skin = self::extractTextureIdFromUrl($textureData['textures']['SKIN']['url']);
50
                }
51
52
                if (isset($textureData['textures']['CAPE']['url'])) {
53
                    $cape = self::extractTextureIdFromUrl($textureData['textures']['CAPE']['url']);
54
                }
55
            }
56
        }
57
58
        return new MojangAccount($uuid, $username, $skin, $cape);
59
    }
60
}
61