RandomOrgAPI::getApiKey()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
ccs 0
cts 0
cp 0
crap 2
rs 10
c 2
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace drupol\Yaroc;
6
7
use BadFunctionCallException;
8
use drupol\Yaroc\Http\Client;
9
use drupol\Yaroc\Plugin\ProviderInterface;
10
use InvalidArgumentException;
11
use RuntimeException;
12
use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface;
13
use Symfony\Contracts\HttpClient\HttpClientInterface;
14
use Symfony\Contracts\HttpClient\ResponseInterface;
15
16
final class RandomOrgAPI implements RandomOrgAPIInterface
17
{
18
    /**
19
     * The configuration.
20
     */
21
    private array $configuration;
22
23
    /**
24
     * The default Random.org endpoint.
25
     */
26
    private string $endpoint = 'https://api.random.org/json-rpc/2/invoke';
27
28
    /**
29
     * The HTTP client.
30
     */
31
    private HttpClientInterface $httpClient;
32
33
    public function __construct(?HttpClientInterface $httpClient = null, array $configuration = [])
34
    {
35
        $this->httpClient = new Client($httpClient);
36
        $this->configuration = $configuration;
37
    }
38
39
    public function call(ProviderInterface $methodPlugin): ResponseInterface
40
    {
41
        $parameters = $methodPlugin->getParameters() +
42
            ['apiKey' => $this->getApiKey()];
43
44
        try {
45
            $response = $methodPlugin
46
                ->withEndPoint($this->getEndPoint())
47
                ->withHttpClient($this->getHttpClient())
48
                ->withParameters($parameters)
49
                ->request();
50 10
        } catch (HttpExceptionInterface $exception) {
51
            throw $exception;
52 10
        }
53 10
54 10
        return $this->validateResponse($response);
55
    }
56 10
57 10
    public function get(ProviderInterface $methodPlugin): array
58
    {
59
        return $this->call($methodPlugin)->toArray();
60 10
    }
61 10
62
    public function getApiKey(): string
63
    {
64
        $configuration = $this->getConfiguration();
65
66
        return $configuration['apiKey'] ?? '';
67 10
    }
68
69 10
    public function getConfiguration(): array
70 10
    {
71
        return $this->configuration;
72 10
    }
73
74
    public function getData(ProviderInterface $methodPlugin): ?array
75 10
    {
76
        return $this->get($methodPlugin)['result']['random']['data'] ?? null;
77 10
    }
78
79 10
    public function getEndPoint(): string
80 10
    {
81
        return $this->endpoint;
82
    }
83 10
84 10
    public function getHttpClient(): HttpClientInterface
85
    {
86
        return $this->httpClient;
87
    }
88
89 3
    public function withApiKey(string $apikey): RandomOrgAPIInterface
90
    {
91 3
        $clone = clone $this;
92
93 3
        $configuration = $clone->getConfiguration();
94 3
        $configuration['apiKey'] = $apikey;
95 3
        $clone->configuration = $configuration;
96
97 3
        return $clone;
98
    }
99
100
    public function withEndPoint(string $endpoint): RandomOrgAPIInterface
101
    {
102
        $clone = clone $this;
103 2
        $clone->endpoint = $endpoint;
104
105 2
        return $clone;
106 2
    }
107
108 2
    public function withHttpClient(HttpClientInterface $client): RandomOrgAPIInterface
109
    {
110
        $clone = clone $this;
111
        $clone->httpClient = $client;
112
113
        return $clone;
114 1
    }
115
116 1
    /**
117 1
     * Validate the response.
118
     *
119 1
     * @throws \Symfony\Contracts\HttpClient\Exception\ExceptionInterface
120
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
121
     */
122
    private function validateResponse(ResponseInterface $response): ResponseInterface
123
    {
124
        if (200 === $response->getStatusCode()) {
125 6
            try {
126
                $body = $response->toArray();
127 6
            } catch (HttpExceptionInterface $exception) {
128
                throw $exception;
129
            }
130
131
            if (isset($body['error']['code'])) {
132
                switch ($body['error']['code']) {
133 6
                    case -32600:
134
                        throw new InvalidArgumentException(
135 6
                            'Invalid Request: ' . $body['error']['message'],
136
                            $body['error']['code']
137 6
                        );
138
139
                    case -32601:
140
                        throw new BadFunctionCallException(
141
                            'Procedure not found: ' . $body['error']['message'],
142
                            $body['error']['code']
143 5
                        );
144
145 5
                    case -32602:
146 5
                        throw new InvalidArgumentException(
147
                            'Invalid arguments: ' . $body['error']['message'],
148 5
                            $body['error']['code']
149
                        );
150 5
151 5
                    case -32603:
152 5
                        throw new RuntimeException(
153 5
                            'Internal Error: ' . $body['error']['message'],
154
                            $body['error']['code']
155
                        );
156
157
                    default:
158
                        throw new RuntimeException(
159
                            'Invalid request/response: ' . $body['error']['message'],
160 3
                            $body['error']['code']
161
                        );
162 3
                }
163
            }
164 3
        }
165 3
166 3
        return $response;
167 3
    }
168
}
169