Completed
Pull Request — master (#38)
by Dániel
01:58
created

BattlenetHttpClient::createMockResponse()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.2728
c 0
b 0
f 0
cc 5
nc 2
nop 1
1
<?php
2
3
namespace Xklusive\BattlenetApi;
4
5
use GuzzleHttp\Psr7;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\HandlerStack;
8
use GuzzleHttp\Psr7\Request;
9
use GuzzleHttp\Psr7\Response;
10
use Illuminate\Support\Collection;
11
use GuzzleHttp\Handler\MockHandler;
12
use GuzzleHttp\Exception\ClientException;
13
use GuzzleHttp\Exception\ServerException;
14
use GuzzleHttp\Exception\RequestException;
15
use Illuminate\Contracts\Cache\Repository;
16
17
/**
18
 * @author Guillaume Meheust <[email protected]>
19
 */
20
class BattlenetHttpClient
21
{
22
    /**
23
     * @var Repository
24
     */
25
    protected $cache;
26
27
    /**
28
     * @var string
29
     */
30
    protected $cacheKey = 'xklusive.battlenetapi.cache';
31
32
    /**
33
     * Http client.
34
     *
35
     * @var object GuzzleHttp\Client
36
     */
37
    protected $client;
38
39
    /**
40
     * Game name for url prefix.
41
     *
42
     * @var string
43
     */
44
    protected $gameParam;
45
46
    /**
47
     * Battle.net Connection Options.
48
     *
49
     * @var Collection
50
     */
51
    protected $options;
52
53
    /**
54
     * BattlnetHttpClient constructor.
55
     *
56
     * @param $repository Illuminate\Contracts\Cache\Repository
57
     */
58
    public function __construct(Repository $repository)
59
    {
60
        $this->cache = $repository;
61
        $this->client = new Client([
62
            'base_uri' => $this->getApiEndPoint(),
63
        ]);
64
    }
65
66
    /**
67
     * Creates a Mock Response based on the given array.
68
     * Used to imitate API response from Blizzard, without calling the actual API.
69
     *
70
     * @param $responses array
71
     */
72
    public function createMockResponse(array $responses = null)
73
    {
74
        $returnStack = collect([]);
75
76
        if ($responses) {
77
            foreach ($responses as $response) {
78
                if ($response->has('code') and $response->has('response')) {
79
                    $stream = Psr7\stream_for($response->get('response'));
80
                    $api_response = new Response(
81
                    $response->get('code'),
82
                    ['Content-Type' => 'application/json'],
83
                    $stream
84
                );
85
                    $returnStack->push($api_response);
86
                }
87
            }
88
        }
89
90
        $mock = new MockHandler($returnStack->toArray());
91
        $this->setGuzzHandler(HandlerStack::create($mock));
92
    }
93
94
    /**
95
     * Create a new client with the given handler.
96
     * Right now only used for testing.
97
     *
98
     * @param $handler GuzzleHttp\HandlerStack
99
     */
100
    protected function setGuzzHandler(HandlerStack $handler = null)
101
    {
102
        if ($handler) {
103
            $this->client = new Client([
104
        'handler' => $handler,
105
        'base_uri' => $this->getApiEndPoint(),
106
            ]);
107
        }
108
    }
109
110
    /**
111
     * Make request with API url and specific URL suffix.
112
     *
113
     * @return Collection|ClientException
114
     */
115
    protected function api()
116
    {
117
        $maxAttempts = 0;
118
        $attempts = 0;
119
	$statusCode = null;
120
	$reasonPhrease = null;
0 ignored issues
show
Unused Code introduced by
$reasonPhrease is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
121
122
        $serverCodes = collect([
123
        '504' => collect([
124
                'message' => 'Gateway Time-out',
125
                'retry' => 3,
126
        ]),
127
        ]);
128
129
        do {
130
            try {
131
                $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...
132
                $response = collect(json_decode($response->getBody()->getContents()));
133
134
                if ($attempts > 0) {
135
                    $response->put('attempts', $attempts);
136
                }
137
138
                return $response;
139
            } catch (ServerException $e) {
140
                // Catch Server errors ( return code 5xx )
141
                if ($e->hasResponse()) {
142
                    $statusCode = $e->getResponse()->getStatusCode();
143
                    $reasonPhrase = $e->getResponse()->getReasonPhrase();
144
                }
145
146
                if ($serverCodes->has($statusCode)) {
147
                    if ($serverCodes->get($statusCode)->get('message') == $reasonPhrase) {
0 ignored issues
show
Bug introduced by
The variable $reasonPhrase does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
148
                        $maxAttempts = $serverCodes->get($statusCode)->get('retry');
149
                        $attempts++;
150
                        continue;
151
                    }
152
                }
153
            } catch (ClientException $e) {
154
                // @TODO: Handle the ClientException ( HTTP 4xx codes )
155
                if ($e->hasResponse()) {
156
                    $statusCode = $e->getResponse()->getStatusCode();
157
                    $reasonPhrase = $e->getResponse()->getReasonPhrase();
158
                }
159
            } catch (RequestException $e) {
160
                // @TODO: Handle the RequestException ( when the provided domain is not valid )
161
                if ($e->hasResponse()) {
162
                    $statusCode = $e->getResponse()->getStatusCode();
163
                    $reasonPhrase = $e->getResponse()->getReasonPhrase();
164
		} else {
165
		    $statusCode = 909;
166
		    $reasonPhrase = 'Unable to resolve API domain';
167
		}
168
            }
169
        } while ($attempts < $maxAttempts);
170
171
        if ($statusCode and $reasonPhrase) {
172
            return collect([
173
                'error' => collect([
174
                'code' => $statusCode,
175
                'message' => $reasonPhrase,
176
                'attempts' => $attempts,
177
            ]),
178
        ]);
179
        }
180
181
        throw $e;
182
    }
183
184
    /**
185
     * Cache the api response data if cache set to true in config file.
186
     *
187
     * @param array  $options   Options
188
     * @param  string $method   method name
189
     * @param string $apiEndPoint
190
     * @return Collection|ClientException
191
     */
192
    public function cache($apiEndPoint, array $options, $method)
193
    {
194
        // Make sure the options we got is a collection
195
        $options = $this->wrapCollection($options);
196
197
        $this->options = $this->getQueryOptions($options);
198
        $this->apiEndPoint = $this->gameParam.$apiEndPoint;
199
200
        $this->buildCahceOptions($method);
201
202
        if ($this->options->has('cache')) {
203
            // The cache options are defined we need to cache the results
204
            return $this->cache->remember(
205
                $this->options->get('cache')->get('uniqKey'),
206
                $this->options->get('cache')->get('duration'),
207
                function () {
208
                    return $this->api();
209
                }
210
            );
211
        }
212
213
        return $this->api();
214
    }
215
216
    /**
217
     * Get default query options from configuration file.
218
     *
219
     * @return Collection
220
     */
221
    private function getDefaultOptions()
222
    {
223
        return collect([
224
            'locale' => $this->getLocale(),
225
            'apikey' => $this->getApiKey(),
226
        ]);
227
    }
228
229
    /**
230
     * Set default option if a 'query' key is provided
231
     * else create 'query' key with default options.
232
     *
233
     * @param Collection $options
234
     *
235
     * @return Collection api response
236
     */
237
    private function getQueryOptions(Collection $options)
238
    {
239
        // Make sure the query object is a collection.
240
        $query = $this->wrapCollection($options->get('query'));
241
242
        foreach ($this->getDefaultOptions() as $key => $option) {
243
            if ($query->has($key) === false) {
244
                $query->put($key, $option);
245
            }
246
        }
247
248
        $options->put('query', $query);
249
250
        return $options;
251
    }
252
253
    /**
254
     * Get API domain provided in configuration.
255
     *
256
     * @return string
257
     */
258
    private function getApiEndPoint()
259
    {
260
        return config('battlenet-api.domain');
261
    }
262
263
    /**
264
     * Get API key provided in configuration.
265
     *
266
     * @return string
267
     */
268
    private function getApiKey()
269
    {
270
        return config('battlenet-api.api_key');
271
    }
272
273
    /**
274
     * Get API locale provided in configuration.
275
     *
276
     * @return string
277
     */
278
    private function getLocale()
279
    {
280
        return config('battlenet-api.locale', 'eu');
281
    }
282
283
    /**
284
     * This method wraps the given value in a collection when applicable.
285
     *
286
     * @return Collection
287
     */
288
    public function wrapCollection($collection)
289
    {
290
        if (is_a($collection, Collection::class) === true) {
291
            return $collection;
292
        }
293
294
        return collect($collection);
295
    }
296
297
    /**
298
     * Build the cache configuration.
299
     *
300
     * @param string $method
301
     */
302
    private function buildCahceOptions($method)
303
    {
304
        if (config('battlenet-api.cache', true)) {
305
            if ($this->options->has('cache') === false) {
306
                // We don't have any cache options yet, build it from ground up.
307
                $cacheOptions = collect();
308
309
                $cacheOptions->put('method', snake_case($method));
310
                $cacheOptions->put('uniqKey', implode('.', [$this->cacheKey, $cacheOptions->get('method')]));
311
                $cacheOptions->put('duration', config('battlenet-api.cache_duration', 600));
312
313
                $this->options->put('cache', $cacheOptions);
314
            }
315
        }
316
    }
317
}
318