Completed
Push — master ( 571af6...74c049 )
by Pol
01:47
created

RandomOrgAPI::withApiKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
cc 1
eloc 6
nc 1
nop 1
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
     * @SuppressWarnings(PHPMD.StaticAccess)
46
     */
47 9
    public function __construct(HttpClient $httpClient = null, array $configuration = [])
48
    {
49 9
        $this->httpClient = $httpClient ?? HttpClientDiscovery::find();
50
51 9
        $dotenv = new Dotenv();
52
53 9
        $files = array_filter(
54
            [
55 9
                __DIR__ . '/../.env.dist',
56
                __DIR__ . '/../.env'
57
            ],
58 9
            'file_exists'
59
        );
60 9
        $dotenv->load(...$files);
61
62 9
        if ($apikey = getenv('RANDOM_ORG_APIKEY')) {
63 9
            $configuration += ['apiKey' => $apikey];
64
        }
65
66 9
        $this->configuration = $configuration;
67 9
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 3
    public function withApiKey(string $apikey) :RandomOrgAPIInterface
73
    {
74 3
        $clone = clone $this;
75
76 3
        $configuration = $clone->getConfiguration();
77 3
        $configuration['apiKey'] = $apikey;
78 3
        $clone->configuration = $configuration;
79
80 3
        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 5
    public function getEndPoint() :string
109
    {
110 5
        return $this->endpoint;
111
    }
112
113
    /**
114
     * {@inheritdoc}
115
     */
116 5
    public function getApiKey() :string
117
    {
118 5
        $configuration = $this->getConfiguration();
119
120 5
        return isset($configuration['apiKey']) ? $configuration['apiKey'] : '';
121
    }
122
123
    /**
124
     * {@inheritdoc}
125
     */
126 4
    public function call(ProviderInterface $methodPlugin) :ResponseInterface
127
    {
128 4
        $parameters = $methodPlugin->getParameters() +
129 4
            ['apiKey' => $this->getApiKey()];
130
131 4
        return $this->validateResponse(
132
            $methodPlugin
133 4
                ->withEndPoint($this->getEndPoint())
134 4
                ->withHttpClient($this->getHttpClient())
135 4
                ->withParameters($parameters)
136 4
                ->request()
137
        );
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143 2
    public function get(ProviderInterface $methodPlugin) :array
144
    {
145 2
        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 2
                ->call($methodPlugin)
148 2
                ->getBody()
149 2
                ->getContents(),
150 2
            true
151
        );
152
    }
153
154
    /**
155
     * {@inheritdoc}
156
     */
157 1
    public function getData(ProviderInterface $methodPlugin)
158
    {
159 1
        $data = $this->get($methodPlugin);
160
161 1
        if (!isset($data['result'])) {
162
            return false;
163
        }
164
165 1
        if (isset($data['result']['random']['data'])) {
166 1
            return $data['result']['random']['data'];
167
        }
168
169
        return false;
170
    }
171
172
    /**
173
     * {@inheritdoc}
174
     */
175 6
    public function getConfiguration() :array
176
    {
177 6
        return $this->configuration;
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183 5
    public function getHttpClient() :HttpClient
184
    {
185 5
        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 4
    private function validateResponse(ResponseInterface $response) :ResponseInterface
196
    {
197 4
        if (200 === $response->getStatusCode()) {
198 4
            $body = json_decode((string) $response->getBody()->getContents(), true);
199
200 4
            if (isset($body['error']['code'])) {
201 1
                switch ($body['error']['code']) {
202 1 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 1
                    case -32601:
208 1
                        throw new \BadFunctionCallException(
209 1
                            'Procedure not found: ' . $body['error']['message'],
210 1
                            $body['error']['code']
211
                        );
212 1 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 1
                        throw new \InvalidArgumentException(
214 1
                            'Invalid arguments: ' . $body['error']['message'],
215 1
                            $body['error']['code']
216
                        );
217 1 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 1
                        throw new \RuntimeException(
224 1
                            'Invalid request/response: ' . $body['error']['message'],
225 1
                            $body['error']['code']
226
                        );
227
                }
228
            }
229
        }
230
231 3
        $response->getBody()->rewind();
232
233 3
        return $response;
234
    }
235
}
236