Completed
Push — master ( f29513...87a330 )
by Pol
02:23
created

RandomOrgAPI::getData()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4.5923

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
ccs 4
cts 6
cp 0.6667
rs 9.2
cc 4
eloc 5
nc 3
nop 0
crap 4.5923
1
<?php
2
3
namespace drupol\Yaroc;
4
5
use drupol\Yaroc\Http\Client;
6
use drupol\Yaroc\Plugin\MethodPluginInterface;
7
use drupol\Yaroc\Plugin\MethodPluginManager;
8
use Http\Client\Common\Plugin;
9
use Http\Client\HttpClient;
10
use Http\Message\UriFactory;
11
use Psr\Http\Message\ResponseInterface;
12
13
/**
14
 * Class RandomOrgAPIClient
15
 *
16
 * @package drupol\Yaroc
17
 */
18
class RandomOrgAPI {
0 ignored issues
show
Complexity introduced by Pol Dellaiera
The class RandomOrgAPI has a coupling between objects value of 13. Consider to reduce the number of dependencies under 13.
Loading history...
19
20
  /**
21
   * The default Random.org endpoint template.
22
   *
23
   * @var string;
24
   */
25
  protected $endpoint = 'https://api.random.org/json-rpc/%s/invoke';
26
27
  /**
28
   * The Random.org api key.
29
   *
30
   * @var string
31
   */
32
  protected $apiKey = '';
33
34
  /**
35
   * The HTTP client.
36
   *
37
   * @var Client
38
   */
39
  protected $httpClient;
40
41
  /**
42
   * The Method plugin manager.
43
   *
44
   * @var MethodPluginManager
45
   */
46
  protected $methodPluginManager;
47
48
  /**
49
   * The Random.org API version.
50
   *
51
   * @var int
52
   */
53
  protected $apiVersion = 1;
54
55
  /**
56
   * The response if any.
57
   *
58
   * @var bool|ResponseInterface
59
   */
60
  protected $response = FALSE;
61
62
  /**
63
   * @var MethodPluginInterface
64
   */
65
  protected $methodPlugin = FALSE;
66
67
  /**
68
   * RandomOrgAPI constructor.
69
   *
70
   * @param null|\Http\Client\HttpClient $httpClient
71
   *   The HTTP client.
72
   */
73 17
  public function __construct(HttpClient $httpClient = NULL) {
74 17
    $this->setHttpClient($httpClient);
75 17
    $this->setMethodPluginManager(new MethodPluginManager());
76 17
    $this->setApiVersion($this->getApiVersion());
77 17
  }
78
79
  /**
80
   * Set the Random.org API Key.
81
   *
82
   * @param string $key
83
   *   The API Key.
84
   *
85
   * @return self
86
   */
87 17
  public function setApiKey($key) {
88 17
    $this->apiKey = $key;
89
90 17
    return $this;
91
  }
92
93
  /**
94
   * Get the Random.org API Key.
95
   *
96
   * @return string
97
   *   The API Key.
98
   */
99 14
  public function getApiKey() {
100 14
    return $this->apiKey;
101
  }
102
103
  /**
104
   * Set the API version.
105
   *
106
   * @param int
107
   *   The API version.
108
   *
109
   * @return self
110
   */
111 17
  public function setApiVersion($version) {
112 17
    $this->apiVersion = $version;
113 17
    $this->getHttpClient()->setEndpoint($this->getEndpoint());
114
115 17
    return $this;
116
  }
117
118
  /**
119
   * Get the API version.
120
   *
121
   * @return int
122
   */
123 17
  public function getApiVersion() {
124 17
    return $this->apiVersion;
125
  }
126
127
  /**
128
   * Set the Random.org endpoint template.
129
   *
130
   * @param string $uri
131
   *   The URI.
132
   *
133
   * @return self
134
   */
135 2
  public function setEndpoint($uri) {
136 2
    $this->endpoint = $uri;
137 2
    $this->getHttpClient()->setEndpoint($this->getEndpoint());
138
139 2
    return $this;
140
  }
141
142
  /**
143
   * Get the Random.org endpoint.
144
   *
145
   * @return string
146
   */
147 18
  public function getEndpoint() {
148 18
    return sprintf($this->endpoint, $this->getApiVersion());
149
  }
150
151
  /**
152
   * Set the client request.
153
   *
154
   * @param null|HttpClient $httpClient
155
   *   The client request.
156
   * @param null|UriFactory $uriFactory
157
   *   The URI Factory.
158
   * @param Plugin[] $plugins
159
   *   The HTTP plugins.
160
   *
161
   * @return self
162
   */
163 17
  public function setHttpClient(HttpClient $httpClient = NULL, UriFactory $uriFactory = NULL, array $plugins = array()) {
164
    $defaultPlugins = [
165 17
      new Plugin\HeaderDefaultsPlugin([
166 17
        'Content-Type' => 'application/json',
167 17
        'User-Agent' => 'YAROC (http://github.com/drupol/yaroc)',
168 17
      ])
169 17
    ];
170
171 17
    $plugins = array_merge(array_values($defaultPlugins), array_values($plugins));
0 ignored issues
show
Coding Style introduced by Pol Dellaiera
Consider using a different name than the parameter $plugins. This often makes code more readable.
Loading history...
172 17
    $this->httpClient = new Client($httpClient, $uriFactory, $plugins);
173 17
    $this->httpClient->setEndpoint($this->getEndpoint());
174
175 17
    return $this;
176
  }
177
178
  /**
179
   * Get the Http client.
180
   *
181
   * @return Client
182
   */
183 17
  public function getHttpClient() {
184 17
    return $this->httpClient;
185
  }
186
187
  /**
188
   * Set the method plugin.
189
   *
190
   * @param \drupol\Yaroc\Plugin\MethodPluginInterface|NULL $methodPlugin
191
   *
192
   * @return False|self
193
   *   Return itself, or FALSE otherwise.
194
   */
195 13
  public function setMethodPlugin(MethodPluginInterface $methodPlugin = NULL) {
196 13
    $this->methodPlugin = $methodPlugin;
197
198 13
    return $methodPlugin ? $this : FALSE;
199
  }
200
201
  /**
202
   * Get the method plugin.
203
   *
204
   * @return \drupol\Yaroc\Plugin\MethodPluginInterface
205
   */
206 13
  private function getMethodPlugin() {
207 13
    return $this->methodPlugin;
208
  }
209
210
  /**
211
   * Set the Method plugin manager.
212
   *
213
   * @param MethodPluginManager $methodPluginManager
214
   *   The method plugin manager.
215
   *
216
   * @return self
217
   */
218 17
  public function setMethodPluginManager(MethodPluginManager $methodPluginManager) {
219 17
    $this->methodPluginManager = $methodPluginManager;
220
221 17
    return $this;
222
  }
223
224
  /**
225
   * Return the Method plugin manager.
226
   *
227
   * @return \drupol\Yaroc\Plugin\MethodPluginManager
228
   */
229 14
  public function getMethodPluginManager() {
230 14
    return $this->methodPluginManager;
231
  }
232
233
  /**
234
   * Set the response.
235
   *
236
   * @param \Psr\Http\Message\ResponseInterface|NULL $response
237
   *
238
   * @return self
239
   */
240 13
  private function setResponse(ResponseInterface $response = NULL) {
241 13
    $this->response = $response;
242
243 13
    return $this;
244
  }
245
246
  /**
247
   * Get the response.
248
   *
249
   * @return bool|\Psr\Http\Message\ResponseInterface
250
   */
251 14
  public function getResponse() {
252 14
    return $this->response;
253
  }
254
255
  /**
256
   * @param \drupol\Yaroc\Plugin\MethodPluginInterface $methodPlugin
257
   *
258
   * @return ResponseInterface|\Exception
259
   */
260 14
  private function request(MethodPluginInterface $methodPlugin) {
261 14
    return $this->httpClient->request($methodPlugin);
262
  }
263
264
  /**
265
   * Call Random.org API.
266
   *
267
   * @param string $method
268
   *   The method to call.
269
   * @param array $params
270
   *   The associative array of params as defined in the Random.org API.
271
   *
272
   * @return self
273
   *   Returns itself.
274
   */
275 17
  public function call($method, array $params = array()) {
276 17
    $this->setResponse(NULL);
277 17
    $this->setMethodPlugin(NULL);
278
279 17
    $params += ['apiKey' => $this->getApiKey()];
280
281 17
    if ($plugin = $this->getMethodPluginManager()->getPlugin($method, $params)) {
282 15
      $this->setMethodPlugin($plugin)->setResponse(
0 ignored issues
show
Bug introduced by Pol Dellaiera
It seems like $plugin defined by $this->getMethodPluginMa...lugin($method, $params) on line 281 can also be of type boolean; however, drupol\Yaroc\RandomOrgAPI::setMethodPlugin() does only seem to accept null|object<drupol\Yaroc...\MethodPluginInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
283 15
        $this->request(
0 ignored issues
show
Bug introduced by Pol Dellaiera
It seems like $this->request($this->ge...this->getApiVersion())) targeting drupol\Yaroc\RandomOrgAPI::request() can also be of type object<Exception>; however, drupol\Yaroc\RandomOrgAPI::setResponse() does only seem to accept null|object<Psr\Http\Message\ResponseInterface>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
284 15
          $this->getMethodPlugin()->setApiVersion($this->getApiVersion()
285 15
          )
286 15
        )
287 14
      );
288 14
    }
289
290 16
    return $this;
291
  }
292
293
  /**
294
   * Get the result array from the response.
295
   *
296
   * @param string $key
0 ignored issues
show
Documentation introduced by Pol Dellaiera
Should the type for parameter $key not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
297
   *   The key you want to get.
298
   *
299
   * @return array|bool
300
   *   The result array, FALSE otherwise.
301
   */
302 13
  public function get($key = NULL) {
303 13
    if ($this->getResponse() && $this->getMethodPlugin()) {
304 13
      if ($result = $this->getMethodPlugin()->get($this->getResponse(), $key)) {
0 ignored issues
show
Bug introduced by Pol Dellaiera
It seems like $this->getResponse() targeting drupol\Yaroc\RandomOrgAPI::getResponse() can also be of type boolean; however, drupol\Yaroc\Plugin\MethodPluginInterface::get() does only seem to accept object<Psr\Http\Message\ResponseInterface>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
305 13
        return $result;
306
      }
307 12
    }
308
309 12
    return FALSE;
310
  }
311
312
  /**
313
   * Get the result array from the response.
314
   *
315
   * @param string $key
0 ignored issues
show
Documentation introduced by Pol Dellaiera
Should the type for parameter $key not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
316
   *   The key you want to get.
317
   *
318
   * @return array|bool
319
   *   The result array, FALSE otherwise.
320
   */
321 14
  public function getFromResult($key = NULL) {
322 14
    if ($result = $this->get('result')) {
323 13
      if ($key && isset($result[$key])) {
0 ignored issues
show
Bug Best Practice introduced by Pol Dellaiera
The expression $key of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
324
        return $result[$key];
325
      }
326 13
      if (is_null($key)) {
327 13
        return $result;
328
      }
329 12
    }
330
331 13
    return FALSE;
332
  }
333
334
  /**
335
   * Get the data from the result array.
336
   *
337
   * @return array|bool
338
   *   The data array, FALSE otherwise.
339
   */
340 12
  public function getData() {
341 12
    if ($result = $this->get('result')) {
342 12
      if (isset($result['random']) && isset($result['random']['data'])) {
343 12
        return $result['random']['data'];
344
      }
345
    }
346
347
    return FALSE;
348
  }
349
350
}
351