Passed
Push — master ( 9aa048...898b5e )
by Mattia
04:05
created

MojangAccountFactory::makeFromApiResponse()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 16
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 30
rs 8.8333
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|null
32
     */
33
    public static function makeFromApiResponse(array $response): ?MojangAccount
34
    {
35
        if (!\array_key_exists('id', $response) || !\array_key_exists('name', $response)) {
36
            return null;
37
        }
38
39
        $uuid = $response['id'];
40
        $username = $response['name'];
41
        $skin = '';
42
        $cape = '';
43
44
        if (\array_key_exists('properties', $response)) {
45
            $textures = \array_filter($response['properties'], static function ($entry) {
46
                return $entry['name'] === 'textures';
47
            });
48
49
            if (!empty($textures)) {
50
                $textureData = \json_decode(\base64_decode($textures[0]['value'], true), true, 512, JSON_THROW_ON_ERROR);
51
52
                if (isset($textureData['textures']['SKIN']['url'])) {
53
                    $skin = self::extractTextureIdFromUrl($textureData['textures']['SKIN']['url']);
54
                }
55
56
                if (isset($textureData['textures']['CAPE']['url'])) {
57
                    $cape = self::extractTextureIdFromUrl($textureData['textures']['CAPE']['url']);
58
                }
59
            }
60
        }
61
62
        return new MojangAccount($uuid, $username, $skin, $cape);
63
    }
64
}
65