Completed
Push — master ( 61323d...82f5dc )
by
unknown
17s queued 10s
created

Client::getServiceResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 4
cp 1
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Syntax\SteamApi;
4
5
use stdClass;
6
use GuzzleHttp\Client as GuzzleClient;
7
use GuzzleHttp\Psr7\Request;
8
use Exception;
9
use GuzzleHttp\Exception\ClientErrorResponseException;
10
use GuzzleHttp\Exception\ServerErrorResponseException;
11
use Syntax\SteamApi\Exceptions\ApiCallFailedException;
12
use Syntax\SteamApi\Exceptions\ClassNotFoundException;
13
14
/**
15
 * @method \Syntax\SteamApi\Steam\News       news()
16
 * @method \Syntax\SteamApi\Steam\Player     player($steamId)
17
 * @method \Syntax\SteamApi\Steam\User       user($steamId)
18
 * @method \Syntax\SteamApi\Steam\User\Stats userStats($steamId)
19
 * @method \Syntax\SteamApi\Steam\App        app()
20
 * @method \Syntax\Steamapi\Steam\Package    package()
21
 * @method \Syntax\SteamApi\Steam\Group      group()
22
 * @method \Syntax\SteamApi\Steam\Item       item($appId)
23
 */
24
class Client
25
{
26
    use SteamId;
27
28
    public $validFormats = ['json', 'xml', 'vdf'];
29
30
    protected $url = 'http://api.steampowered.com/';
31
32
    protected $client;
33
34
    protected $interface;
35
36
    protected $method;
37
38
    protected $version = 'v0002';
39
40
    protected $apiKey;
41
42
    protected $apiFormat = 'json';
43
44
    protected $steamId;
45
46
    protected $isService = false;
47
48 41
    public function __construct()
49
    {
50 41
        $apiKey = $this->getApiKey();
51
52 41
        $this->client = new GuzzleClient();
53 41
        $this->apiKey = $apiKey;
54
55
        // Set up the Ids
56 41
        $this->setUpFormatted();
57 41
    }
58
59
    public function get()
60
    {
61
        return $this;
62
    }
63
64 1
    public function getSteamId()
65
    {
66 1
        return $this->steamId;
67
    }
68
69
    /**
70
     * @param string $arguments
71
     *
72
     * @return string
73
     *
74
     * @throws ApiArgumentRequired
75
     * @throws ApiCallFailedException
76
     */
77 9
    protected function setUpService($arguments = null)
78
    {
79
        // Services have a different url syntax
80 9
        if ($arguments == null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $arguments of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
81
            throw new ApiArgumentRequired;
82
        }
83
84
        $parameters = [
85 9
            'key'        => $this->apiKey,
86 9
            'format'     => $this->apiFormat,
87 9
            'input_json' => $arguments,
88
        ];
89
90 9
        $steamUrl = $this->buildUrl(true);
91
92
        // Build the query string
93 9
        $parameters = http_build_query($parameters);
94
95
        // Send the request and get the results
96 9
        $request  = new Request('GET', $steamUrl . '?' . $parameters);
97 9
        $response = $this->sendRequest($request);
98
99
        // Pass the results back
100 9
        return $response->body;
101
    }
102
103 14
    protected function setUpClient(array $arguments = [])
104
    {
105 14
        $versionFlag = ! is_null($this->version);
106 14
        $steamUrl    = $this->buildUrl($versionFlag);
107
108
        $parameters = [
109 14
            'key'    => $this->apiKey,
110 14
            'format' => $this->apiFormat,
111
        ];
112
113 14
        if (! empty($arguments)) {
114 14
            $parameters = array_merge($arguments, $parameters);
115
        }
116
117
        // Build the query string
118 14
        $parameters = http_build_query($parameters);
119
120 14
        $headers = [];
121 14
        if (array_key_exists('l', $arguments)) {
122
            $headers = [
123 4
                'Accept-Language' => $arguments['l'],
124
            ];
125
        }
126
127
        // Send the request and get the results
128 14
        $request  = new Request('GET', $steamUrl . '?' . $parameters, $headers);
129 14
        $response = $this->sendRequest($request);
130
131
        // Pass the results back
132 14
        return $response->body;
133
    }
134
135 4
    protected function setUpXml(array $arguments = [])
136
    {
137 4
        $steamUrl = $this->buildUrl();
138
139
        // Build the query string
140 4
        $parameters = http_build_query($arguments);
141
142
        // Pass the results back
143 4
        return simplexml_load_file($steamUrl . '?' . $parameters);
144
        libxml_use_internal_errors(true);
0 ignored issues
show
Unused Code introduced by
libxml_use_internal_errors(true); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
145
        $result = simplexml_load_file($steamUrl . '?' . $parameters);
146
147
        if (! $result) {
148
            return null;
149
        }
150
151
        return $result;
152
    }
153
154 1
    public function getRedirectUrl()
155
    {
156 1
        $ch = curl_init();
157 1
        curl_setopt($ch, CURLOPT_URL, $this->url);
158 1
        curl_setopt($ch, CURLOPT_HEADER, true);
159 1
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
160 1
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
161
162 1
        curl_exec($ch);
163 1
        $this->url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
164 1
        curl_close($ch);
165 1
    }
166
167
    /**
168
     * @param \GuzzleHttp\Psr7\Request $request
169
     *
170
     * @return \stdClass
171
     * @throws \Syntax\SteamApi\Exceptions\ApiCallFailedException
172
     */
173 23
    protected function sendRequest(Request $request)
174
    {
175
        // Try to get the result.  Handle the possible exceptions that can arise
176
        try {
177 23
            $response = $this->client->send($request);
178
179 23
            $result       = new stdClass();
180 23
            $result->code = $response->getStatusCode();
181 23
            $result->body = json_decode($response->getBody(true));
0 ignored issues
show
Unused Code introduced by
The call to ResponseInterface::getBody() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
182
        } catch (ClientErrorResponseException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientErrorResponseException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
183
            throw new ApiCallFailedException($e->getMessage(), $e->getResponse()->getStatusCode(), $e);
184
        } catch (ServerErrorResponseException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ServerErrorResponseException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
185
            throw new ApiCallFailedException('Api call failed to complete due to a server error.', $e->getResponse()->getStatusCode(), $e);
186
        } catch (Exception $e) {
187
            throw new ApiCallFailedException($e->getMessage(), $e->getCode(), $e);
188
        }
189
190
        // If all worked out, return the result
191 23
        return $result;
192
    }
193
194 27
    private function buildUrl($version = false)
195
    {
196
        // Set up the basic url
197 27
        $url = $this->url . $this->interface . '/' . $this->method . '/';
198
199
        // If we have a version, add it
200 27
        if ($version) {
201 21
            return $url . $this->version . '/';
202
        }
203
204 6
        return $url;
205
    }
206
207 30
    public function __call($name, $arguments)
208
    {
209
        // Handle a steamId being passed
210 30
        if (! empty($arguments) && count($arguments) == 1) {
211 24
            $this->steamId = $arguments[0];
212
213 24
            $this->convertSteamIdTo64();
214
        }
215
216
        // Inside the root steam directory
217 30
        $class      = ucfirst($name);
218 30
        $steamClass = '\Syntax\SteamApi\Steam\\' . $class;
219
220 30
        if (class_exists($steamClass)) {
221 26
            return new $steamClass($this->steamId);
222
        }
223
224
        // Inside a nested directory
225 4
        $class      = implode('\\', preg_split('/(?=[A-Z])/', $class, -1, PREG_SPLIT_NO_EMPTY));
226 4
        $steamClass = '\Syntax\SteamApi\Steam\\' . $class;
227
228 4
        if (class_exists($steamClass)) {
229 4
            return new $steamClass($this->steamId);
230
        }
231
232
        // Nothing found
233
        throw new ClassNotFoundException($name);
234
    }
235
236
    /**
237
     * @param Collection $objects
238
     *
239
     * @return $this
240
     */
241 6
    protected function sortObjects($objects)
242
    {
243
        return $objects->sortBy(function ($object) {
244 6
            return $object->name;
245 6
        });
246
    }
247
248
    /**
249
     * @param string $method
250
     * @param string $version
251
     */
252 9
    protected function setApiDetails($method, $version)
253
    {
254 9
        $this->method  = $method;
255 9
        $this->version = $version;
256 9
    }
257
258 9
    protected function getServiceResponse($arguments)
259
    {
260 9
        $arguments = json_encode($arguments);
261
262
        // Get the client
263 9
        $client = $this->setUpService($arguments)->response;
264
265 9
        return $client;
266
    }
267
268
    /**
269
     * @return string
270
     * @throws Exceptions\InvalidApiKeyException
271
     */
272 41
    protected function getApiKey()
273
    {
274 41
        $apiKey = \Config::get('steam-api.steamApiKey');
275
276 41
        if ($apiKey == 'YOUR-API-KEY') {
277
            throw new Exceptions\InvalidApiKeyException();
278
        }
279 41
        if (is_null($apiKey) || $apiKey == '' || $apiKey == []) {
280 41
            $apiKey = getenv('apiKey');
281
        }
282
283 41
        return $apiKey;
284
    }
285
286 24
    private function convertSteamIdTo64()
287
    {
288 24
        if (is_array($this->steamId)) {
289
            array_walk($this->steamId, function (&$id) {
290
                // Convert the id to all types and grab the 64 bit version
291 1
                $id = $this->convertToAll($id)->id64;
292 1
            });
293
        } else {
294
            // Convert the id to all types and grab the 64 bit version
295 23
            $this->steamId = $this->convertToAll($this->steamId)->id64;
296
        }
297 24
    }
298
}
299