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

RandomOrgAPI::getEndPoint()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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