Completed
Push — master ( 32f0b1...030226 )
by Ezra
14s queued 12s
created

Client::getServiceResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Syntax\SteamApi;
4
5
use GuzzleHttp\Exception\GuzzleException;
6
use Illuminate\Support\Collection;
7
use Illuminate\Support\Facades\Config;
8
use stdClass;
9
use GuzzleHttp\Client as GuzzleClient;
10
use GuzzleHttp\Psr7\Request;
11
use Exception;
12
use GuzzleHttp\Exception\ClientException;
13
use GuzzleHttp\Exception\ServerException;
14
use Syntax\SteamApi\Exceptions\ApiArgumentRequired;
15
use Syntax\SteamApi\Exceptions\ApiCallFailedException;
16
use Syntax\SteamApi\Exceptions\ClassNotFoundException;
17
use Syntax\SteamApi\Steam\App;
18
use Syntax\SteamApi\Steam\Group;
19
use Syntax\SteamApi\Steam\Item;
20
use Syntax\SteamApi\Steam\News;
21
use Syntax\Steamapi\Steam\Package;
22
use Syntax\SteamApi\Steam\Player;
23
use Syntax\SteamApi\Steam\User;
24
use Syntax\SteamApi\Steam\User\Stats;
25
26
/**
27
 * @method News       news()
28
 * @method Player     player($steamId)
29
 * @method User       user($steamId)
30
 * @method Stats      userStats($steamId)
31
 * @method App        app()
32
 * @method Package    package()
33
 * @method Group      group()
34
 * @method Item       item($appId)
35
 */
36
class Client
37
{
38 1
    use SteamId;
39
40
    public $validFormats = ['json', 'xml', 'vdf'];
41
42
    protected $url = 'http://api.steampowered.com/';
43
44
    protected $client;
45
46
    protected $interface;
47
48
    protected $method;
49
50
    protected $version = 'v0002';
51
52
    protected $apiKey;
53
54
    protected $apiFormat = 'json';
55
56
    protected $steamId;
57
58
    protected $isService = false;
59
60 27
    public function __construct()
61
    {
62 27
        $apiKey = $this->getApiKey();
63
64 27
        $this->client = new GuzzleClient();
65 27
        $this->apiKey = $apiKey;
66
67
        // Set up the Ids
68 27
        $this->setUpFormatted();
69 27
    }
70
71
    public function get()
72
    {
73
        return $this;
74
    }
75
76 1
    public function getSteamId()
77
    {
78 1
        return $this->steamId;
79
    }
80
81
    /**
82
     * @param string $arguments
83
     *
84
     * @return string
85
     *
86
     * @throws ApiArgumentRequired
87
     * @throws ApiCallFailedException
88
     * @throws GuzzleException
89
     */
90
    protected function setUpService($arguments = null)
91
    {
92
        // Services have a different url syntax
93
        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...
94
            throw new ApiArgumentRequired;
95
        }
96
97
        $parameters = [
98
            'key'        => $this->apiKey,
99
            'format'     => $this->apiFormat,
100
            'input_json' => $arguments,
101
        ];
102
103
        $steamUrl = $this->buildUrl(true);
104
105
        // Build the query string
106
        $parameters = http_build_query($parameters);
107
108
        // Send the request and get the results
109
        $request  = new Request('GET', $steamUrl . '?' . $parameters);
110
        $response = $this->sendRequest($request);
111
112
        // Pass the results back
113
        return $response->body;
114
    }
115
116 8
    protected function setUpClient(array $arguments = [])
117
    {
118 8
        $versionFlag = ! is_null($this->version);
119 8
        $steamUrl    = $this->buildUrl($versionFlag);
120
121
        $parameters = [
122 8
            'key'    => $this->apiKey,
123 8
            'format' => $this->apiFormat,
124
        ];
125
126 8
        if (! empty($arguments)) {
127 7
            $parameters = array_merge($arguments, $parameters);
128
        }
129
130
        // Build the query string
131 8
        $parameters = http_build_query($parameters);
132
133 8
        $headers = [];
134 8
        if (array_key_exists('l', $arguments)) {
135
            $headers = [
136 5
                'Accept-Language' => $arguments['l'],
137
            ];
138
        }
139
140
        // Send the request and get the results
141 8
        $request  = new Request('GET', $steamUrl . '?' . $parameters, $headers);
142 8
        $response = $this->sendRequest($request);
143
144
        // Pass the results back
145 6
        return $response->body;
146
    }
147
148 4
    protected function setUpXml(array $arguments = [])
149
    {
150 4
        $steamUrl = $this->buildUrl();
151
152
        // Build the query string
153 4
        $parameters = http_build_query($arguments);
154
155
        // Pass the results back
156 4
        libxml_use_internal_errors(true);
157 4
        $result = simplexml_load_file($steamUrl . '?' . $parameters);
158
159 4
        if (! $result) {
160 1
            return null;
161
        }
162
163 3
        return $result;
164
    }
165
166 1
    public function getRedirectUrl()
167
    {
168 1
        $ch = curl_init();
169 1
        curl_setopt($ch, CURLOPT_URL, $this->url);
170 1
        curl_setopt($ch, CURLOPT_HEADER, true);
171 1
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
172 1
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
173
174 1
        curl_exec($ch);
175 1
        $this->url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
176 1
        curl_close($ch);
177 1
    }
178
179
    /**
180
     * @param Request $request
181
     *
182
     * @return stdClass
183
     * @throws ApiCallFailedException
184
     * @throws GuzzleException
185
     */
186 8
    protected function sendRequest(Request $request)
187
    {
188
        // Try to get the result.  Handle the possible exceptions that can arise
189
        try {
190 8
            $response = $this->client->send($request);
191
192 6
            $result       = new stdClass();
193 6
            $result->code = $response->getStatusCode();
194 6
            $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...
195 2
        } catch (ClientException $e) {
196 2
            throw new ApiCallFailedException($e->getMessage(), $e->getResponse()->getStatusCode(), $e);
197
        } catch (ServerException $e) {
198
            throw new ApiCallFailedException('Api call failed to complete due to a server error.', $e->getResponse()->getStatusCode(), $e);
199
        } catch (Exception $e) {
200
            throw new ApiCallFailedException($e->getMessage(), $e->getCode(), $e);
201
        }
202
203
        // If all worked out, return the result
204 6
        return $result;
205
    }
206
207 12
    private function buildUrl($version = false)
208
    {
209
        // Set up the basic url
210 12
        $url = $this->url . $this->interface . '/' . $this->method . '/';
211
212
        // If we have a version, add it
213 12
        if ($version) {
214 6
            return $url . $this->version . '/';
215
        }
216
217 6
        return $url;
218
    }
219
220 15
    public function __call($name, $arguments)
221
    {
222
        // Handle a steamId being passed
223 15
        if (! empty($arguments) && count($arguments) == 1) {
224 8
            $this->steamId = $arguments[0];
225
226 8
            $this->convertSteamIdTo64();
227
        }
228
229
        // Inside the root steam directory
230 15
        $class      = ucfirst($name);
231 15
        $steamClass = '\Syntax\SteamApi\Steam\\' . $class;
232
233 15
        if (class_exists($steamClass)) {
234 10
            return new $steamClass($this->steamId);
235
        }
236
237
        // Inside a nested directory
238 5
        $class      = implode('\\', preg_split('/(?=[A-Z])/', $class, -1, PREG_SPLIT_NO_EMPTY));
239 5
        $steamClass = '\Syntax\SteamApi\Steam\\' . $class;
240
241 5
        if (class_exists($steamClass)) {
242 5
            return new $steamClass($this->steamId);
243
        }
244
245
        // Nothing found
246
        throw new ClassNotFoundException($name);
247
    }
248
249
    /**
250
     * @param Collection $objects
251
     *
252
     * @return Collection
253
     */
254 2
    protected function sortObjects($objects)
255
    {
256 2
        return $objects->sortBy(function ($object) {
257 2
            return $object->name;
258 2
        });
259
    }
260
261
    /**
262
     * @param string $method
263
     * @param string $version
264
     */
265
    protected function setApiDetails($method, $version)
266
    {
267
        $this->method  = $method;
268
        $this->version = $version;
269
    }
270
271
    protected function getServiceResponse($arguments)
272
    {
273
        $arguments = json_encode($arguments);
274
275
        // Get the client
276
        return $this->setUpService($arguments)->response;
277
    }
278
279
    /**
280
     * @return string
281
     * @throws Exceptions\InvalidApiKeyException
282
     */
283 27
    protected function getApiKey()
284
    {
285 27
        $apiKey = Config::get('steam-api.steamApiKey');
286
287 27
        if ($apiKey == 'YOUR-API-KEY') {
288
            throw new Exceptions\InvalidApiKeyException();
289
        }
290 27
        if (is_null($apiKey) || $apiKey == '' || $apiKey == []) {
291 27
            $apiKey = getenv('apiKey');
292
        }
293
294 27
        return $apiKey;
295
    }
296
297 8
    private function convertSteamIdTo64()
298
    {
299 8
        if (is_array($this->steamId)) {
300 1
            array_walk($this->steamId, function (&$id) {
301
                // Convert the id to all types and grab the 64 bit version
302 1
                $id = $this->convertToAll($id)->id64;
303 1
            });
304
        } else {
305
            // Convert the id to all types and grab the 64 bit version
306 7
            $this->steamId = $this->convertToAll($this->steamId)->id64;
307
        }
308 8
    }
309
}
310