Completed
Push — master ( 50abcd...1c0c1a )
by Travis
03:16
created

Client::getRedirectUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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