GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 69229a...5d27ce )
by Krzysztof
03:17
created

Client::getClientVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Coinpaprika;
4
5
use Coinpaprika\Exception\RateLimitExceededException;
6
use Coinpaprika\Exception\ResponseErrorException;
7
use Coinpaprika\Model\Coin;
8
use Coinpaprika\Model\GlobalStats;
9
use Coinpaprika\Model\Ticker;
10
use JMS\Serializer\SerializerBuilder;
11
use JMS\Serializer\Serializer;
12
use GuzzleHttp\Exception\GuzzleException;
13
use Psr\Http\Message\ResponseInterface;
14
15
/**
16
 * Class Client
17
 *
18
 * @package Coinpaprika
19
 *
20
 * @author Krzysztof Przybyszewski <[email protected]>
21
 */
22
class Client
23
{
24
    const BASE_URL = 'https://api.coinpaprika.com/%ver%/';
25
26
    /**
27
     * @var string
28
     */
29
    private $apiVersion;
30
31
    /**
32
     * @var \GuzzleHttp\Client
33
     */
34
    private $httpClient;
35
36
    /**
37
     * @var Serializer
38
     */
39
    private $serializer;
40
41
    /**
42
     * Client constructor.
43
     *
44
     * @param string|null        $cacheDir
45
     * @param \GuzzleHttp\Client $httpClient
46
     */
47 7
    public function __construct(
48
        string $cacheDir = null,
49
        \GuzzleHttp\Client $httpClient = null
50
    ) {
51 7
        $serializerBuilder = SerializerBuilder::create()
52 7
            ->addMetadataDir(__DIR__.'/Resource/config/serializer');
53
54 7
        if ($cacheDir !== null) {
55 1
            $serializerBuilder->setCacheDir($cacheDir);
56
        }
57
58 7
        $this->apiVersion = 'v1';
59 7
        $this->serializer = $serializerBuilder->build();
60
61 7
        if ($httpClient === null) {
62 1
            $httpClient = new \GuzzleHttp\Client();
63
        }
64
65 7
        $this->httpClient = $httpClient;
66 7
    }
67
68
    /**
69
     * Get global stats
70
     *
71
     * @throws GuzzleException
72
     * @throws ResponseErrorException
73
     * @throws RateLimitExceededException
74
     *
75
     * @return GlobalStats
76
     */
77 1
    public function getGlobalStats(): GlobalStats
78
    {
79 1
        $response = $this->sendRequest('GET', $this->getEndpointUrl('global'));
80
81 1
        return $this->deserializeResponse($response, GlobalStats::class);
82
    }
83
84
    /**
85
     * Get tickers
86
     *
87
     * @throws GuzzleException
88
     * @throws ResponseErrorException
89
     * @throws RateLimitExceededException
90
     *
91
     * @return array|Ticker[]
92
     */
93 1
    public function getTickers(): array
94
    {
95 1
        $response = $this->sendRequest('GET', $this->getEndpointUrl('ticker'));
96
97 1
        return $this->deserializeResponse($response, sprintf('array<%s>', Ticker::class));
98
    }
99
100
    /**
101
     * Get coin`s ticker data
102
     *
103
     * @param string $id
104
     *
105
     * @throws GuzzleException
106
     * @throws ResponseErrorException
107
     * @throws RateLimitExceededException
108
     *
109
     * @return Ticker
110
     */
111 3
    public function getTickerByCoinId(string $id): Ticker
112
    {
113 3
        $response = $this->sendRequest(
114 3
            'GET',
115 3
            $this->getEndpointUrl(sprintf('ticker/%s', $id))
116
        );
117
118 3
        return $this->deserializeResponse($response, Ticker::class);
119
    }
120
121
    /**
122
     * Get coins list
123
     *
124
     * @throws GuzzleException
125
     * @throws ResponseErrorException
126
     * @throws RateLimitExceededException
127
     *
128
     * @return array|Coin[]
129
     */
130 1
    public function getCoins(): array
131
    {
132 1
        $response = $this->sendRequest('GET', $this->getEndpointUrl('coins'));
133
134 1
        return $this->deserializeResponse($response, sprintf('array<%s>', Coin::class));
135
136
    }
137
138
    /**
139
     * Get the endpoint URL.
140
     *
141
     * @param string $endpoint
142
     *
143
     * @return string
144
     */
145 6
    protected function getEndpointUrl(string $endpoint): string
146
    {
147 6
        return str_replace('%ver%', $this->getApiVersion(), static::BASE_URL).$endpoint;
148
    }
149
150
    /**
151
     * Get the API version
152
     *
153
     * @return string
154
     */
155 7
    public function getApiVersion(): string
156
    {
157 7
        return $this->apiVersion;
158
    }
159
160
    /**
161
     * @param string $method
162
     * @param string $url
163
     * @param array  $headers
164
     *
165
     * @return ResponseInterface
166
     * @throws GuzzleException
167
     */
168 6
    protected function sendRequest(string $method, string $url, array $headers = []): ResponseInterface
169
    {
170
        $defaultHeaders = [
171 6
            'User-Agent' => 'Coinpaprika API Client - PHP'
172
        ];
173
174 6
        return $this->httpClient->request($method, $url, [
175 6
            'headers' => array_merge($defaultHeaders, $headers)
176
        ]);
177
    }
178
179
    /**
180
     * Unmarshal JSON
181
     *
182
     * @param ResponseInterface $response
183
     * @param string            $type
184
     *
185
     * @throws ResponseErrorException
186
     * @throws RateLimitExceededException
187
     *
188
     * @return mixed
189
     */
190 6
    protected function deserializeResponse(ResponseInterface $response, string $type)
191
    {
192 6
        $body = $response->getBody();
193
194
        // rate limit exceeded
195 6
        if ($response->getStatusCode() === 429) {
196 1
            throw new RateLimitExceededException('Response code from API 429. Rate limit exceeded.');
197
        }
198
199 5
        if (array_key_exists('error', $e = json_decode($body, true))) {
200 1
            throw new ResponseErrorException($e['error']);
201
        }
202
203 4
        return $this->serializer->deserialize($body, $type, 'json');
204
    }
205
}
206