Completed
Push — master ( abb8e6...4c98df )
by Peter
01:41
created

Client::sendRequest()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 10
cts 10
cp 1
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 11
nc 5
nop 1
crap 5
1
<?php
2
3
namespace PtrTn\Battlerite;
4
5
use GuzzleHttp\ClientInterface;
6
use GuzzleHttp\Exception\ClientException;
7
use GuzzleHttp\Psr7\Request;
8
use InvalidArgumentException;
9
use Psr\Http\Message\ResponseInterface;
10
use PtrTn\Battlerite\Dto\Match;
11
use PtrTn\Battlerite\Dto\Matches;
12
use PtrTn\Battlerite\Dto\Player;
13
use PtrTn\Battlerite\Dto\Players;
14
use PtrTn\Battlerite\Exception\FailedRequestException;
15
use PtrTn\Battlerite\Exception\InvalidRequestException;
16
use PtrTn\Battlerite\Exception\InvalidResourceException;
17
use PtrTn\Battlerite\Query\MatchesQuery;
18
use PtrTn\Battlerite\Query\PlayersQuery;
19
20
class Client
21
{
22
    private const BASE_URL = 'https://api.dc01.gamelockerapp.com/shards/global';
23
24
    /**
25
     * @var ClientInterface
26
     */
27
    private $httpClient;
28
    /**
29
     * @var string
30
     */
31
    private $apiKey;
32
33 13
    public function __construct(ClientInterface $httpClient, string $apiKey)
34
    {
35 13
        $this->httpClient = $httpClient;
36 13
        $this->apiKey = $apiKey;
37 13
    }
38
39 8
    public function getMatches(MatchesQuery $query = null): Matches
40
    {
41 8
        $request = $this->createRequestForEndpoint(
42 8
            '/matches',
43 8
            $query ? $query->toQueryString() : null
44
        );
45 8
        $response = $this->sendRequest($request);
46
47 5
        $responseData = $this->getDataFromResponse($response);
48 3
        return Matches::createFromArray($responseData);
49
    }
50
51 2
    public function getMatch(string $matchId): Match
52
    {
53 2
        $request = $this->createRequestForEndpoint('/matches/' . $matchId);
54 2
        $response = $this->sendRequest($request);
55
56 1
        $responseData = $this->getDataFromResponse($response);
57 1
        return Match::createFromArray($responseData['data']);
58
    }
59
60 2
    public function getPlayers(PlayersQuery $query = null): Players
61
    {
62 2
        $request = $this->createRequestForEndpoint(
63 2
            '/players',
64 2
            $query ? $query->toQueryString() : null
65
        );
66 2
        $response = $this->sendRequest($request);
67
68 2
        $responseData = $this->getDataFromResponse($response);
69 2
        return Players::createFromArray($responseData);
70
    }
71
72 1
    public function getPlayer(string $playerId): Player
73
    {
74 1
        $request = $this->createRequestForEndpoint('/players/' . $playerId);
75 1
        $response = $this->sendRequest($request);
76
77 1
        $responseData = $this->getDataFromResponse($response);
78 1
        return Player::createFromArray($responseData['data']);
79
    }
80
81 13
    private function createRequestForEndpoint(string $endpoint, string $query = null): Request
82
    {
83 13
        $uri = self::BASE_URL . $endpoint;
84 13
        if (isset($query)) {
85 2
            $uri .= '?' . $query;
86
        }
87
88 13
        return new Request(
89 13
            'GET',
90 13
            $uri,
91
            [
92 13
                'Accept' => 'application/json',
93 13
                'Authorization' => $this->apiKey
94
            ]
95
        );
96
    }
97
98 13
    private function sendRequest($request): ResponseInterface
99
    {
100
        try {
101 13
            return $this->httpClient->send($request);
102 4
        } catch (ClientException $e) {
103 4
            if ($e->getResponse()->getStatusCode() === 401) {
104 1
                throw InvalidRequestException::invalidApiKey($this->apiKey);
105
            }
106 3
            if ($e->getResponse()->getStatusCode() === 429) {
107 1
                throw InvalidRequestException::rateLimitReached();
108
            }
109 2
            if ($e->getResponse()->getStatusCode() === 404) {
110 1
                throw InvalidResourceException::resourceNotFound();
111
            }
112
113 1
            throw FailedRequestException::createForException($e);
114
        }
115
    }
116
117 9
    private function getDataFromResponse(ResponseInterface $response): array
118
    {
119 9
        $responseBody = $response->getBody()->getContents();
120 9
        if (!isset($responseBody) || $responseBody === '') {
121 1
            throw new FailedRequestException('No response');
122
        }
123
124
        try {
125 8
            $responseData = \GuzzleHttp\json_decode($responseBody, true);
126 1
        } catch (InvalidArgumentException $e) {
127 1
            throw FailedRequestException::invalidResponseJson($e);
128
        }
129
130 7
        return $responseData;
131
    }
132
}
133