Completed
Push — master ( 1bdaea...d13912 )
by Dániel
13s
created

BattlenetHttpClient::wrapCollection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace Xklusive\BattlenetApi;
4
5
use GuzzleHttp\Client;
6
use Illuminate\Support\Collection;
7
use GuzzleHttp\Exception\ClientException;
8
use GuzzleHttp\Exception\RequestException;
9
use Illuminate\Contracts\Cache\Repository;
10
11
/**
12
 * @author Guillaume Meheust <[email protected]>
13
 */
14
class BattlenetHttpClient
15
{
16
    /**
17
     * @var Repository
18
     */
19
    protected $cache;
20
21
    /**
22
     * @var string
23
     */
24
    protected $cacheKey = 'xklusive.battlenetapi.cache';
25
26
    /**
27
     * Http client.
28
     *
29
     * @var object GuzzleHttp\Client
30
     */
31
    protected $client;
32
33
    /**
34
     * Game name for url prefix.
35
     *
36
     * @var string
37
     */
38
    protected $gameParam;
39
40
    /**
41
     * Battle.net Connection Options.
42
     *
43
     * @var Collection
44
     */
45
    protected $options;
46
47
    /**
48
     * BattlnetHttpClient constructor.
49
     */
50
    public function __construct(Repository $repository)
51
    {
52
        $this->cache = $repository;
53
        $this->client = new Client([
54
            'base_uri' => $this->getApiEndPoint(),
55
        ]);
56
    }
57
58
    /**
59
     * Make request with API url and specific URL suffix.
60
     *
61
     * @return Collection|ClientException
62
     */
63
    protected function api()
64
    {
65
        $maxAttempts = 0;
66
        $attempts = 0;
67
68
        $statusCodes = [
69
            // Currently all status codes except the 503 is disabled and not handled
70
            '504' => [
71
                'message' => 'Gateway Timeout',
72
                'retry' => 6,
73
            ],
74
        ];
75
76
        do {
77
            try {
78
                $response = $this->client->get($this->apiEndPoint, $this->options->toArray());
0 ignored issues
show
Bug introduced by
The property apiEndPoint does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
79
80
                return collect(json_decode($response->getBody()->getContents()));
81
            } catch (ClientException $e) {
82
                $statusCode = $e->getResponse()->getStatusCode();
83
                $reasonPhrase = $e->getResponse()->getReasonPhrase();
84
85
                if (array_key_exists($statusCode, $statusCodes)) {
86
                    if ($statusCodes[$statusCode]['message'] == $reasonPhrase) {
87
                        $maxAttempts = $statusCodes[$statusCode]['retry'];
88
                        $attempts++;
89
                        continue;
90
                    }
91
                }
92
            } catch (RequestException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
93
                // @TODO: Handle the RequestException ( when the provided domain is not valid )
94
            }
95
        } while ($attempts < $maxAttempts);
96
97
        return $e;
98
    }
99
100
    /**
101
     * Cache the api response data if cache set to true in config file.
102
     *
103
     * @param array  $options   Options
104
     * @param  string $method   method name
105
     * @param string $apiEndPoint
106
     * @return Collection|ClientException
107
     */
108
    public function cache($apiEndPoint, array $options, $method)
109
    {
110
        // Make sure the options we got is a collection
111
        $options = $this->wrapCollection($options);
112
113
        $this->options = $this->getQueryOptions($options);
114
        $this->apiEndPoint = $this->gameParam.$apiEndPoint;
115
116
        $this->buildCahceOptions($method);
117
118
        if ($this->options->has('cache')) {
119
            // The cache options are defined we need to cache the results
120
            return $this->cache->remember(
121
                $this->options->get('cache')->get('uniqKey'),
122
                $this->options->get('cache')->get('duration'),
123
                function () {
124
                    return $this->api();
125
                }
126
            );
127
        }
128
129
        return $this->api();
130
    }
131
132
    /**
133
     * Get default query options from configuration file.
134
     *
135
     * @return Collection
136
     */
137
    private function getDefaultOptions()
138
    {
139
        return collect([
140
            'locale' => $this->getLocale(),
141
            'apikey' => $this->getApiKey(),
142
        ]);
143
    }
144
145
    /**
146
     * Set default option if a 'query' key is provided
147
     * else create 'query' key with default options.
148
     *
149
     * @param Collection $options
150
     *
151
     * @return Collection api response
152
     */
153
    private function getQueryOptions(Collection $options)
154
    {
155
        // Make sure the query object is a collection.
156
        $query = $this->wrapCollection($options->get('query'));
157
158
        foreach ($this->getDefaultOptions() as $key => $option) {
159
            if ($query->has($key) === false) {
160
                $query->put($key, $option);
161
            }
162
        }
163
164
        $options->put('query', $query);
165
166
        return $options;
167
    }
168
169
    /**
170
     * Get API domain provided in configuration.
171
     *
172
     * @return string
173
     */
174
    private function getApiEndPoint()
175
    {
176
        return config('battlenet-api.domain');
177
    }
178
179
    /**
180
     * Get API key provided in configuration.
181
     *
182
     * @return string
183
     */
184
    private function getApiKey()
185
    {
186
        return config('battlenet-api.api_key');
187
    }
188
189
    /**
190
     * Get API locale provided in configuration.
191
     *
192
     * @return string
193
     */
194
    private function getLocale()
195
    {
196
        return config('battlenet-api.locale', 'eu');
197
    }
198
199
    /**
200
     * This method wraps the given value in a collection when applicable.
201
     *
202
     * @return Collection
203
     */
204
    public function wrapCollection($collection)
205
    {
206
        if (is_a($collection, Collection::class) === true) {
207
            return $collection;
208
        }
209
210
        return collect($collection);
211
    }
212
213
    /**
214
     * Build the cache configuration.
215
     *
216
     * @param string $method
217
     */
218
    private function buildCahceOptions($method)
219
    {
220
        if (config('battlenet-api.cache', true)) {
221
            if ($this->options->has('cache') === false) {
222
                // We don't have any cache options yet, build it from ground up.
223
                $cacheOptions = collect();
224
225
                $cacheOptions->put('method', snake_case($method));
226
                $cacheOptions->put('uniqKey', implode('.', [$this->cacheKey, $cacheOptions->get('method')]));
227
                $cacheOptions->put('duration', config('battlenet-api.cache_duration', 600));
228
229
                $this->options->put('cache', $cacheOptions);
230
            }
231
        }
232
    }
233
}
234