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

RandomOrgAPI::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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