GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( fb8f70...fcb615 )
by Cees-Jan
12:21 queued 02:24
created

Client   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 270
Duplicated Lines 2.22 %

Coupling/Cohesion

Components 1
Dependencies 14

Test Coverage

Coverage 96.84%

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 14
dl 6
loc 270
ccs 92
cts 95
cp 0.9684
rs 10
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 3 12 3
A determineHydrator() 3 14 4
A ensureCommandHandlers() 0 15 2
A checkCache() 0 20 2
A storeCache() 0 18 2
A determineCacheKey() 0 15 1
A stripExtraSlashes() 0 4 1
B request() 0 52 6
A applyApiSettingsToRequest() 0 10 1
A getHeaders() 0 8 1
A getHydrator() 0 4 1
A getLoop() 0 4 1
A getBaseURL() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php declare(strict_types=1);
2
3
namespace ApiClients\Foundation\Transport;
4
5
use ApiClients\Foundation\Hydrator\Factory as HydratorFactory;
6
use ApiClients\Foundation\Hydrator\Hydrator;
7
use ApiClients\Foundation\Hydrator\Options as HydratorOptions;
8
use ApiClients\Foundation\Transport\CommandBus;
9
use GuzzleHttp\Client as GuzzleClient;
10
use GuzzleHttp\Psr7\Request as Psr7Request;
11
use GuzzleHttp\Psr7\Response as Psr7Response;
12
use GuzzleHttp\RequestOptions;
13
use Psr\Http\Message\RequestInterface;
14
use Psr\Http\Message\ResponseInterface;
15
use Psr\Http\Message\UriInterface;
16
use React\Cache\CacheInterface;
17
use React\EventLoop\LoopInterface;
18
use React\Promise\PromiseInterface;
19
use function React\Promise\reject;
20
use React\Promise\RejectedPromise;
21
use function React\Promise\resolve;
22
use function WyriHaximus\React\futureFunctionPromise;
23
24
class Client
25
{
26
    const DEFAULT_OPTIONS = [
27
        Options::SCHEMA => 'https',
28
        Options::PATH => '/',
29
        Options::USER_AGENT => 'WyriHaximus/php-api-client',
30
        Options::HEADERS => [],
31
    ];
32
33
    /**
34
     * @var GuzzleClient
35
     */
36
    protected $handler;
37
38
    /**
39
     * @var LoopInterface
40
     */
41
    protected $loop;
42
43
    /**
44
     * @var array
45
     */
46
    protected $options = [];
47
48
    /**
49
     * @var Hydrator
50
     */
51
    protected $hydrator;
52
53
    /**
54
     * @var CacheInterface
55
     */
56
    protected $cache;
57
58
    /**
59
     * @param LoopInterface $loop
60
     * @param GuzzleClient $handler
61
     * @param array $options
62
     */
63 12
    public function __construct(LoopInterface $loop, GuzzleClient $handler, array $options = [])
64
    {
65 12
        $this->loop = $loop;
66 12
        $this->handler = $handler;
67 12
        $this->options = $options + self::DEFAULT_OPTIONS;
68 12
69 3 View Code Duplication
        if (isset($this->options[Options::CACHE]) && $this->options[Options::CACHE] instanceof CacheInterface) {
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...
70
            $this->cache = $this->options[Options::CACHE];
71 12
        }
72 12
73
        $this->hydrator = $this->determineHydrator();
74
    }
75
76
    /**
77
     * @return Hydrator
78 12
     * @throws \Exception
79
     */
80 12
    protected function determineHydrator(): Hydrator
81
    {
82 View Code Duplication
        if (isset($this->options[Options::HYDRATOR]) && $this->options[Options::HYDRATOR] instanceof Hydrator) {
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...
83
            return $this->options[Options::HYDRATOR];
84 12
        }
85
86
        if (!isset($this->options[Options::HYDRATOR_OPTIONS])) {
87
            throw new \Exception('Missing Hydrator options');
88 12
        }
89 12
90
        $this->ensureCommandHandlers();
91
92 12
        return HydratorFactory::create($this->options[Options::HYDRATOR_OPTIONS]);
93
    }
94 12
95
    protected function ensureCommandHandlers()
96
    {
97
        $mapping = [];
98
        if (isset($this->options[Options::HYDRATOR_OPTIONS][HydratorOptions::COMMAND_BUS])) {
99
            $mapping = $this->options[Options::HYDRATOR_OPTIONS][HydratorOptions::COMMAND_BUS];
100
        }
101
102 5
        $requestHandler = new CommandBus\Handler\RequestHandler($this);
103
        $mapping[CommandBus\Command\RequestCommand::class] = $requestHandler;
104
        $mapping[CommandBus\Command\SimpleRequestCommand::class] = $requestHandler;
105 3
        $mapping[CommandBus\Command\JsonEncodeCommand::class] = new CommandBus\Handler\JsonEncodeHandler($this->loop);
106 5
        $mapping[CommandBus\Command\JsonDecodeCommand::class] = new CommandBus\Handler\JsonDecodeHandler($this->loop);
107
108
        $this->options[Options::HYDRATOR_OPTIONS][HydratorOptions::COMMAND_BUS] = $mapping;
109
    }
110
111
    /**
112
     * @param UriInterface $uri
113
     * @return PromiseInterface
114 5
     */
115
    protected function checkCache(UriInterface $uri): PromiseInterface
116 5
    {
117 5
        if (!($this->cache instanceof CacheInterface)) {
118
            return reject();
119
        }
120 3
121 5
        $key = $this->determineCacheKey($uri);
122
        return $this->cache->get($key)->then(function ($document) {
123
            $document = json_decode($document, true);
124
            $response = new Psr7Response(
125
                $document['status_code'],
126
                $document['headers'],
127
                $document['body'],
128 3
                $document['protocol_version'],
129
                $document['reason_phrase']
130 3
            );
131 1
132
            return resolve($response);
133
        });
134 2
    }
135
136 1
    /**
137 1
     * @param RequestInterface $request
138 1
     * @param ResponseInterface $response
139 1
     */
140 1
    protected function storeCache(RequestInterface $request, ResponseInterface $response)
141 1
    {
142 1
        if (!($this->cache instanceof CacheInterface)) {
143
            return;
144
        }
145 1
146 2
        $document = [
147
            'body' => $response->getBody()->getContents(),
148
            'headers' => $response->getHeaders(),
149
            'protocol_version' => $response->getProtocolVersion(),
150
            'reason_phrase' => $response->getReasonPhrase(),
151
            'status_code' => $response->getStatusCode(),
152
        ];
153 2
154
        $key = $this->determineCacheKey($request->getUri());
155 2
156
        $this->cache->set($key, json_encode($document));
157
    }
158
159
    /**
160 2
     * @param UriInterface $uri
161 2
     * @return string
162 2
     */
163 2
    protected function determineCacheKey(UriInterface $uri): string
164 2
    {
165
        return $this->stripExtraSlashes(
166
            implode(
167 2
                '/',
168
                [
169 2
                    $uri->getScheme(),
170 2
                    $uri->getHost(),
171
                    $uri->getPort(),
172
                    $uri->getPath(),
173
                    md5($uri->getQuery()),
174
                ]
175
            )
176 3
        );
177
    }
178 3
179
    /**
180 3
     * @param string $string
181
     * @return string
182 3
     */
183 3
    protected function stripExtraSlashes(string $string): string
184 3
    {
185 3
        return preg_replace('#/+#', '/', $string);
186 3
    }
187
188
    /**
189
     * @param RequestInterface $request
190
     * @param bool $refresh
191
     * @param array $options
192
     * @return PromiseInterface
193
     */
194
    public function request(RequestInterface $request, array $options = [], bool $refresh = false): PromiseInterface
195
    {
196 3
        $promise = new RejectedPromise();
197
198 3
        $request = $this->applyApiSettingsToRequest($request);
199
200
        if ((!isset($options[RequestOptions::STREAM]) || !$options[RequestOptions::STREAM]) && !$refresh) {
201
            $promise = $this->checkCache($request->getUri());
202
        }
203
204
        return $promise->otherwise(function () use ($request, $options) {
205
            return resolve($this->handler->sendAsync(
206 5
                $request,
207
                $options
208 5
            ));
209
        })->then(function (ResponseInterface $response) use ($request, $options, $refresh) {
210 5
            if (isset($options[RequestOptions::STREAM]) && $options[RequestOptions::STREAM] === true) {
211 3
                return resolve(
212
                    new Response(
213
                        '',
214
                        $response
215 4
                    )
216
                );
217 4
            }
218
219
            $contents = $response->getBody()->getContents();
220 2
221 2
            $this->storeCache(
222
                $request,
223 2
                new Psr7Response(
224 2
                    $response->getStatusCode(),
225 2
                    $response->getHeaders(),
226
                    $contents,
227 2
                    $response->getProtocolVersion(),
228 2
                    $response->getReasonPhrase()
229
                )
230
            );
231 2
232 2
            return resolve(
233 2
                new Response(
234 2
                    $contents,
235
                    new Psr7Response(
236 2
                        $response->getStatusCode(),
237 2
                        $response->getHeaders(),
238
                        $contents,
239
                        $response->getProtocolVersion(),
240
                        $response->getReasonPhrase()
241
                    )
242 4
                )
243
            );
244 4
        });
245 5
    }
246
247
    protected function applyApiSettingsToRequest(RequestInterface $request): RequestInterface
248
    {
249
        return new Psr7Request(
250
            $request->getMethod(),
251
            $this->getBaseURL() . $request->getUri(),
252 5
            $this->getHeaders() + $request->getHeaders(),
253
            $request->getBody(),
254 5
            $request->getProtocolVersion()
255 5
        );
256 5
    }
257
258
    /**
259
     * @return array
260
     */
261
    public function getHeaders(): array
262 5
    {
263
        $headers = [
264
            'User-Agent' => $this->options[Options::USER_AGENT],
265 5
        ];
266
        $headers += $this->options[Options::HEADERS];
267 5
        return $headers;
268 5
    }
269
270
    /**
271
     * @return Hydrator
272
     */
273
    public function getHydrator(): Hydrator
274
    {
275
        return $this->hydrator;
276
    }
277 3
278 3
    /**
279 3
     * @return LoopInterface
280
     */
281
    public function getLoop(): LoopInterface
282
    {
283
        return $this->loop;
284
    }
285 1
286
    /**
287 1
     * @return string
288
     */
289
    public function getBaseURL(): string
290
    {
291
        return $this->options[Options::SCHEMA] . '://' . $this->options[Options::HOST] . $this->options[Options::PATH];
292
    }
293
}
294