Completed
Pull Request — master (#2)
by Pol
02:04
created

RandomOrgAPI::getFromResult()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5.0729

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 7
cp 0.8571
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 7
nc 4
nop 1
crap 5.0729
1
<?php
2
3
namespace drupol\Yaroc;
4
5
use drupol\Yaroc\Plugin\ProviderInterface;
6
use Http\Client\HttpClient;
7
use Http\Discovery\HttpClientDiscovery;
8
use Psr\Http\Message\ResponseInterface;
9
10
/**
11
 * Class RandomOrgAPI.
12
 */
13
class RandomOrgAPI implements RandomOrgAPIInterface
14
{
15
    /**
16
     * The default Random.org endpoint.
17
     *
18
     * @var string;
19
     */
20
    private $endpoint = 'https://api.random.org/json-rpc/1/invoke';
21
22
    /**
23
     * The configuration.
24
     *
25
     * @var array
26
     */
27
    private $configuration;
28
29
    /**
30
     * The HTTP client.
31
     *
32
     * @var \Http\Client\HttpClient
33
     */
34
    private $httpClient;
35
36
    /**
37
     * RandomOrgAPI constructor.
38
     *
39
     * @param \Http\Client\HttpClient $httpClient
0 ignored issues
show
Documentation introduced by
Should the type for parameter $httpClient not be null|HttpClient?

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...
40
     *   The HTTP client.
41
     * @param array $configuration
42
     *   The configuration array.
43
     */
44 5
    public function __construct(HttpClient $httpClient = null, array $configuration = [])
45
    {
46 5
        $this->httpClient = $httpClient ?? HttpClientDiscovery::find();
47 5
        $this->configuration = $configuration;
48 5
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53 2
    public function withApiKey(string $apikey) :RandomOrgAPIInterface
54
    {
55 2
        $clone = clone $this;
56
57 2
        $configuration = $clone->getConfiguration();
58 2
        $configuration['apiKey'] = $apikey;
59
60 2
        $clone->configuration = $configuration;
61
62 2
        return $clone;
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 1
    public function withEndPoint(string $endpoint) :RandomOrgAPIInterface
69
    {
70 1
        $clone = clone $this;
71 1
        $clone->endpoint = $endpoint;
72
73 1
        return $clone;
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79 1
    public function withHttpClient(HttpClient $client) :RandomOrgAPIInterface
80
    {
81 1
        $clone = clone $this;
82 1
        $clone->httpClient = $client;
83
84 1
        return $clone;
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90 1
    public function getEndPoint() :string
91
    {
92 1
        return $this->endpoint;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98 1
    public function getApiKey() :string
99
    {
100 1
        $configuration = $this->getConfiguration()
101 1
            + ['apiKey' => ''];
102
103 1
        return $configuration['apiKey'];
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109
    public function call(ProviderInterface $methodPlugin) :ResponseInterface
110
    {
111
        $parameters = $methodPlugin->getParameters() +
112
            ['apiKey' => $this->getApiKey()];
113
114
        return $this->validateResponse(
115
            $methodPlugin
116
                ->withEndPoint($this->getEndPoint())
117
                ->withHttpClient($this->getHttpClient())
118
                ->withParameters($parameters)
119
                ->request()
120
        );
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126
    public function get(ProviderInterface $methodPlugin) :array
127
    {
128
        return json_decode(
129
            (string) $this
0 ignored issues
show
Bug introduced by
The method getBody does only exist in Psr\Http\Message\ResponseInterface, but not in Exception.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
130
                ->call($methodPlugin)
131
                ->getBody()
132
                ->getContents(),
133
            true
134
        );
135
    }
136
137
    /**
138
     * {@inheritdoc}
139
     */
140
    public function getData(ProviderInterface $methodPlugin)
141
    {
142
        $data = $this->get($methodPlugin);
143
144
        if (!isset($data['result'])) {
145
            return false;
146
        }
147
148
        if (isset($data['result']['random']['data'])) {
149
            return $data['result']['random']['data'];
150
        }
151
152
        return false;
153
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158 2
    public function getConfiguration() :array
159
    {
160 2
        return $this->configuration;
161
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166 1
    public function getHttpClient() :HttpClient
167
    {
168 1
        return $this->httpClient;
169
    }
170
171
    /**
172
     * Validate the response.
173
     *
174
     * @param \Psr\Http\Message\ResponseInterface $response
175
     *
176
     * @return \Exception|ResponseInterface
177
     */
178
    private function validateResponse(ResponseInterface $response) :ResponseInterface
179
    {
180
        if (200 === $response->getStatusCode()) {
181
            $body = json_decode((string) $response->getBody()->getContents(), true);
182
183
            if (isset($body['error']['code'])) {
184
                switch ($body['error']['code']) {
185 View Code Duplication
                    case -32600:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186
                        throw new \InvalidArgumentException(
187
                            'Invalid Request: ' . $body['error']['message'],
188
                            $body['error']['code']
189
                        );
190
                    case -32601:
191
                        throw new \BadFunctionCallException(
192
                            'Procedure not found: ' . $body['error']['message'],
193
                            $body['error']['code']
194
                        );
195 View Code Duplication
                    case -32602:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
196
                        throw new \InvalidArgumentException(
197
                            'Invalid arguments: ' . $body['error']['message'],
198
                            $body['error']['code']
199
                        );
200 View Code Duplication
                    case -32603:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
201
                        throw new \RuntimeException(
202
                            'Internal Error: ' . $body['error']['message'],
203
                            $body['error']['code']
204
                        );
205 View Code Duplication
                    default:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
206
                        throw new \RuntimeException(
207
                            'Invalid request/response: ' . $body['error']['message'],
208
                            $body['error']['code']
209
                        );
210
                }
211
            }
212
        }
213
214
        $response->getBody()->rewind();
215
216
        return $response;
217
    }
218
}
219