Completed
Pull Request — master (#2)
by Pol
07:20 queued 05:24
created

RandomOrgAPI::validateResponse()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 40
Code Lines 27

Duplication

Lines 8
Ratio 20 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 8
loc 40
ccs 0
cts 26
cp 0
rs 6.7272
cc 7
eloc 27
nc 7
nop 1
crap 56
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
use Symfony\Component\Dotenv\Dotenv;
10
11
/**
12
 * Class RandomOrgAPI.
13
 */
14
class RandomOrgAPI implements RandomOrgAPIInterface
15
{
16
    /**
17
     * The default Random.org endpoint.
18
     *
19
     * @var string;
20
     */
21
    private $endpoint = 'https://api.random.org/json-rpc/1/invoke';
22
23
    /**
24
     * The configuration.
25
     *
26
     * @var array
27
     */
28
    private $configuration;
29
30
    /**
31
     * The HTTP client.
32
     *
33
     * @var \Http\Client\HttpClient
34
     */
35
    private $httpClient;
36
37
    /**
38
     * RandomOrgAPI constructor.
39
     *
40
     * @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...
41
     *   The HTTP client.
42
     * @param array $configuration
43
     *   The configuration array.
44
     *
45
     * @SuppressWarnings(PHPMD.StaticAccess)
46
     */
47 5
    public function __construct(HttpClient $httpClient = null, array $configuration = [])
48
    {
49 5
        $this->httpClient = $httpClient ?? HttpClientDiscovery::find();
50
51 5
        $dotenv = new Dotenv();
52
53 5
        $files = array_filter(
54
            [
55 5
                __DIR__ . '/../.env.dist',
56
                __DIR__ . '/../.env'
57
            ],
58 5
            'file_exists'
59
        );
60 5
        $dotenv->load(...$files);
61
62 5
        if ($apikey = getenv('RANDOM_ORG_APIKEY')) {
63 5
            $configuration += ['apiKey' => $apikey];
64
        }
65
66 5
        $this->configuration = $configuration;
67 5
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 2
    public function withApiKey(string $apikey) :RandomOrgAPIInterface
73
    {
74 2
        $clone = clone $this;
75
76 2
        $configuration = $clone->getConfiguration();
77 2
        $configuration['apiKey'] = $apikey;
78 2
        $clone->configuration = $configuration;
79
80 2
        return $clone;
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86 1
    public function withEndPoint(string $endpoint) :RandomOrgAPIInterface
87
    {
88 1
        $clone = clone $this;
89 1
        $clone->endpoint = $endpoint;
90
91 1
        return $clone;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97 1
    public function withHttpClient(HttpClient $client) :RandomOrgAPIInterface
98
    {
99 1
        $clone = clone $this;
100 1
        $clone->httpClient = $client;
101
102 1
        return $clone;
103
    }
104
105
    /**
106
     * {@inheritdoc}
107
     */
108 1
    public function getEndPoint() :string
109
    {
110 1
        return $this->endpoint;
111
    }
112
113
    /**
114
     * {@inheritdoc}
115
     */
116 1
    public function getApiKey() :string
117
    {
118 1
        $configuration = $this->getConfiguration();
119
120 1
        return isset($configuration['apiKey']) ? $configuration['apiKey'] : '';
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126
    public function call(ProviderInterface $methodPlugin) :ResponseInterface
127
    {
128
        $parameters = $methodPlugin->getParameters() +
129
            ['apiKey' => $this->getApiKey()];
130
131
        return $this->validateResponse(
132
            $methodPlugin
133
                ->withEndPoint($this->getEndPoint())
134
                ->withHttpClient($this->getHttpClient())
135
                ->withParameters($parameters)
136
                ->request()
137
        );
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143
    public function get(ProviderInterface $methodPlugin) :array
144
    {
145
        return json_decode(
146
            (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...
147
                ->call($methodPlugin)
148
                ->getBody()
149
                ->getContents(),
150
            true
151
        );
152
    }
153
154
    /**
155
     * {@inheritdoc}
156
     */
157
    public function getData(ProviderInterface $methodPlugin)
158
    {
159
        $data = $this->get($methodPlugin);
160
161
        if (!isset($data['result'])) {
162
            return false;
163
        }
164
165
        if (isset($data['result']['random']['data'])) {
166
            return $data['result']['random']['data'];
167
        }
168
169
        return false;
170
    }
171
172
    /**
173
     * {@inheritdoc}
174
     */
175 2
    public function getConfiguration() :array
176
    {
177 2
        return $this->configuration;
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183 1
    public function getHttpClient() :HttpClient
184
    {
185 1
        return $this->httpClient;
186
    }
187
188
    /**
189
     * Validate the response.
190
     *
191
     * @param \Psr\Http\Message\ResponseInterface $response
192
     *
193
     * @return \Exception|ResponseInterface
194
     */
195
    private function validateResponse(ResponseInterface $response) :ResponseInterface
196
    {
197
        if (200 === $response->getStatusCode()) {
198
            $body = json_decode((string) $response->getBody()->getContents(), true);
199
200
            if (isset($body['error']['code'])) {
201
                switch ($body['error']['code']) {
202 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...
203
                        throw new \InvalidArgumentException(
204
                            'Invalid Request: ' . $body['error']['message'],
205
                            $body['error']['code']
206
                        );
207
                    case -32601:
208
                        throw new \BadFunctionCallException(
209
                            'Procedure not found: ' . $body['error']['message'],
210
                            $body['error']['code']
211
                        );
212 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...
213
                        throw new \InvalidArgumentException(
214
                            'Invalid arguments: ' . $body['error']['message'],
215
                            $body['error']['code']
216
                        );
217 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...
218
                        throw new \RuntimeException(
219
                            'Internal Error: ' . $body['error']['message'],
220
                            $body['error']['code']
221
                        );
222 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...
223
                        throw new \RuntimeException(
224
                            'Invalid request/response: ' . $body['error']['message'],
225
                            $body['error']['code']
226
                        );
227
                }
228
            }
229
        }
230
231
        $response->getBody()->rewind();
232
233
        return $response;
234
    }
235
}
236