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
Pull Request — master (#2)
by Cees-Jan
07:18
created

Client::postRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
dl 16
loc 16
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 11
nc 2
nop 3
1
<?php declare(strict_types=1);
2
3
namespace ApiClients\Foundation\Transport;
4
5
use ApiClients\Foundation\Middleware\MiddlewareInterface;
6
use ApiClients\Foundation\Transport\CommandBus;
7
use Clue\React\Buzz\Browser;
8
use GuzzleHttp\Psr7\Request as Psr7Request;
9
use GuzzleHttp\Psr7\Uri;
10
use Interop\Container\ContainerInterface;
11
use Psr\Http\Message\RequestInterface;
12
use Psr\Http\Message\ResponseInterface;
13
use React\EventLoop\LoopInterface;
14
use React\Promise\CancellablePromiseInterface;
15
use React\Promise\PromiseInterface;
16
use function React\Promise\reject;
17
use function React\Promise\resolve;
18
use function WyriHaximus\React\futureFunctionPromise;
19
20
class Client
21
{
22
    const DEFAULT_OPTIONS = [
23
        Options::SCHEMA => 'https',
24
        Options::PATH => '/',
25
        Options::USER_AGENT => 'WyriHaximus/php-api-client',
26
        Options::HEADERS => [],
27
    ];
28
29
    /**
30
     * @var LoopInterface
31
     */
32
    protected $loop;
33
34
    /**
35
     * @var ContainerInterface
36
     */
37
    protected $container;
38
39
    /**
40
     * @var GuzzleClient
41
     */
42
    protected $handler;
43
44
    /**
45
     * @var array
46
     */
47
    protected $options = [];
48
49
    /**
50
     * @var MiddlewareInterface[]
51
     */
52
    protected $middleware = [];
53
54
    /**
55
     * @param LoopInterface $loop
56
     * @param ContainerInterface $container
57
     * @param Browser $buzz
58
     * @param array $options
59
     */
60
    public function __construct(
61
        LoopInterface $loop,
62
        ContainerInterface $container,
63
        Browser $buzz,
64
        array $options = []
65
    ) {
66
        $this->loop = $loop;
67
        $this->container = $container;
68
        $this->handler = $buzz;
0 ignored issues
show
Documentation Bug introduced by
It seems like $buzz of type object<Clue\React\Buzz\Browser> is incompatible with the declared type object<ApiClients\Founda...Transport\GuzzleClient> of property $handler.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
69
        $this->options = $options + self::DEFAULT_OPTIONS;
70
71
        if (isset($this->options[Options::MIDDLEWARE])) {
72
            $this->middleware = $this->options[Options::MIDDLEWARE];
73
        }
74
    }
75 View Code Duplication
    protected function preRequest(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
76
        array $middlewares,
77
        RequestInterface $request,
78
        array $options
79
    ): CancellablePromiseInterface {
80
        $promise = resolve($request);
81
82
        foreach ($middlewares as $middleware) {
83
            $requestMiddleware = $middleware;
84
            $promise = $promise->then(function (RequestInterface $request) use ($options, $requestMiddleware) {
85
                return $requestMiddleware->pre($request, $options);
86
            });
87
        }
88
89
        return $promise;
90
    }
91
92 View Code Duplication
    protected function postRequest(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
93
        array $middlewares,
94
        ResponseInterface $response,
95
        array $options
96
    ): CancellablePromiseInterface {
97
        $promise = resolve($response);
98
99
        foreach ($middlewares as $middleware) {
100
            $responseMiddleware = $middleware;
101
            $promise = $promise->then(function (ResponseInterface $response) use ($options, $responseMiddleware) {
102
                return $responseMiddleware->post($response, $options);
103
            });
104
        }
105
106
        return $promise;
107
    }
108
109
    protected function constructMiddlewares(array $options): array
110
    {
111
        $set = $this->middleware;
112
113
        if (isset($options[Options::MIDDLEWARE])) {
114
            $set = $this->combinedMiddlewares($options[Options::MIDDLEWARE]);
115
        }
116
117
        $middlewares = [];
118
        foreach ($set as $middleware) {
119
            if (!is_subclass_of($middleware, MiddlewareInterface::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \ApiClients\Foundation\M...dlewareInterface::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
120
                continue;
121
            }
122
123
            $middlewares[] = $this->container->get($middleware);
124
        }
125
126
        return $middlewares;
127
    }
128
129
    protected function combinedMiddlewares(array $extraMiddlewares): array
130
    {
131
        $set = $this->middleware;
132
133
        foreach ($extraMiddlewares as $middleware) {
134
            if (in_array($middleware, $set)) {
135
                continue;
136
            }
137
138
            $set[] = $middleware;
139
        }
140
141
        return $set;
142
    }
143
144
    /**
145
     * @param RequestInterface $request
146
     * @param array $options
147
     * @return PromiseInterface
148
     */
149
    public function request(RequestInterface $request, array $options = []): PromiseInterface
150
    {
151
        $request = $this->applyApiSettingsToRequest($request);
152
        $options = $this->applyRequestOptions($options);
153
        $middlewares = $this->constructMiddlewares($options);
154
155
        return $this->preRequest($middlewares, $request, $options)->then(function ($request) use ($options) {
156
            return resolve($this->handler->send(
157
                $request
158
            ));
159
        }, function (ResponseInterface $response) {
160
            return resolve($response);
161
        })->then(function (ResponseInterface $response) use ($middlewares, $options) {
162
            return $this->postRequest($middlewares, $response, $options);
163
        });
164
    }
165
166
    protected function applyApiSettingsToRequest(RequestInterface $request): RequestInterface
167
    {
168
        $uri = $request->getUri();
169
        if (strpos((string)$uri, '://') === false) {
170
            $uri = Uri::resolve(
171
                new Uri(
172
                    $this->options[Options::SCHEMA] .
173
                    '://' .
174
                    $this->options[Options::HOST] .
175
                    $this->options[Options::PATH]
176
                ),
177
                $request->getUri()
178
            );
179
        }
180
181
        return new Psr7Request(
182
            $request->getMethod(),
183
            $uri,
184
            $this->options[Options::HEADERS] + $request->getHeaders(),
185
            $request->getBody(),
186
            $request->getProtocolVersion()
187
        );
188
    }
189
190
    public function applyRequestOptions(array $options): array
191
    {
192
        if (!isset($this->options[Options::DEFAULT_REQUEST_OPTIONS])) {
193
            return $options;
194
        }
195
196
        return array_merge_recursive(
197
            $this->options[Options::DEFAULT_REQUEST_OPTIONS],
198
            $options
199
        );
200
    }
201
}
202