Completed
Pull Request — develop (#333)
by Jens
14:58
created

Guzzle5Adapter::executeAsync()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 0
cts 23
cp 0
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 17
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * @author @jayS-de <[email protected]>
4
 */
5
6
namespace Commercetools\Core\Client\Adapter;
7
8
use Commercetools\Core\Helper\CorrelationIdProvider;
9
use Commercetools\Core\Helper\Subscriber\CorrelationIdSubscriber;
10
use GuzzleHttp\Client;
11
use GuzzleHttp\Exception\RequestException;
12
use GuzzleHttp\Pool;
13
use GuzzleHttp\Psr7\Request;
14
use GuzzleHttp\Psr7\Response;
15
use Psr\Http\Message\RequestInterface;
16
use Psr\Http\Message\ResponseInterface;
17
use Psr\Log\LoggerInterface;
18
use Commercetools\Core\Helper\Subscriber\Log\LogSubscriber;
19
use Commercetools\Core\Error\ApiException;
20
use Psr\Log\LogLevel;
21
22
class Guzzle5Adapter implements AdapterInterface, CorrelationIdAware
23
{
24
    /**
25
     * @var Client
26
     */
27
    protected $client;
28
29
    /**
30
     * @var LoggerInterface
31
     */
32
    protected $logger;
33
34
    /**
35
     * @param array $options
36
     */
37
    public function __construct(array $options = [])
38
    {
39
        if (isset($options['base_uri'])) {
40
            $options['base_url'] = $options['base_uri'];
41
            unset($options['base_uri']);
42
        }
43
        if (isset($options['headers'])) {
44
            $options['defaults']['headers'] = $options['headers'];
45
            unset($options['headers']);
46
        }
47
        $options = array_merge(
48
            [
49
                'allow_redirects' => false,
50
                'verify' => true,
51
                'timeout' => 60,
52
                'connect_timeout' => 10,
53
                'pool_size' => 25
54
            ],
55
            $options
56
        );
57
        $this->client = new Client($options);
58
    }
59
60
    public function setLogger(LoggerInterface $logger, $logLevel = LogLevel::INFO, $formatter = null)
61
    {
62
        $this->logger = $logger;
63
        if ($logger instanceof LoggerInterface) {
64
            $this->getEmitter()->attach(new LogSubscriber($logger, $formatter, $logLevel));
65
        }
66
    }
67
68
    public function addHandler($handler)
69
    {
70
        $this->getEmitter()->attach($handler);
71
    }
72
73
    public function setCorrelationIdProvider(CorrelationIdProvider $provider)
74
    {
75
        $this->getEmitter()->attach(new CorrelationIdSubscriber($provider));
76
    }
77
78
    /**
79
     * @internal
80
     * @return \GuzzleHttp\Event\Emitter|\GuzzleHttp\Event\EmitterInterface
81
     */
82
    public function getEmitter()
83
    {
84
        return $this->client->getEmitter();
85
    }
86
87
    /**
88
     * @param RequestInterface $request
89
     * @return ResponseInterface
90
     * @throws \Commercetools\Core\Error\ApiException
91
     * @throws \Commercetools\Core\Error\BadGatewayException
92
     * @throws \Commercetools\Core\Error\ConcurrentModificationException
93
     * @throws \Commercetools\Core\Error\ErrorResponseException
94
     * @throws \Commercetools\Core\Error\GatewayTimeoutException
95
     * @throws \Commercetools\Core\Error\InternalServerErrorException
96
     * @throws \Commercetools\Core\Error\InvalidTokenException
97
     * @throws \Commercetools\Core\Error\NotFoundException
98
     * @throws \Commercetools\Core\Error\ServiceUnavailableException
99
     */
100
    public function execute(RequestInterface $request)
101
    {
102
        $options = [
103
            'headers' => $request->getHeaders(),
104
            'body' => (string)$request->getBody()
105
        ];
106
107
        try {
108
            $guzzleRequest = $this->client->createRequest($request->getMethod(), (string)$request->getUri(), $options);
0 ignored issues
show
Bug introduced by
The method createRequest() does not exist on GuzzleHttp\Client. Did you maybe mean request()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
109
            $guzzleResponse = $this->client->send($guzzleRequest);
110
            $response = $this->packResponse($guzzleResponse);
0 ignored issues
show
Documentation introduced by
$guzzleResponse is of type object<Psr\Http\Message\ResponseInterface>, but the function expects a null|object<GuzzleHttp\Message\ResponseInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
111
        } catch (RequestException $exception) {
112
            $response = $this->packResponse($exception->getResponse());
0 ignored issues
show
Bug introduced by
It seems like $exception->getResponse() targeting GuzzleHttp\Exception\Req...xception::getResponse() can also be of type object<Psr\Http\Message\ResponseInterface>; however, Commercetools\Core\Clien...Adapter::packResponse() does only seem to accept null|object<GuzzleHttp\Message\ResponseInterface>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
113
            throw ApiException::create($request, $response, $exception);
114
        }
115
116
        return $response;
117
    }
118
119
    protected function packResponse(\GuzzleHttp\Message\ResponseInterface $response = null)
120
    {
121
        if (!$response instanceof \GuzzleHttp\Message\ResponseInterface) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Message\ResponseInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
122
            return null;
123
        }
124
        return new Response(
125
            $response->getStatusCode(),
126
            $response->getHeaders(),
127
            (string)$response->getBody()
128
        );
129
    }
130
131
    /**
132
     * @param RequestInterface[] $requests
133
     * @return \Psr\Http\Message\ResponseInterface[]
134
     * @throws \Commercetools\Core\Error\ApiException
135
     * @throws \Commercetools\Core\Error\BadGatewayException
136
     * @throws \Commercetools\Core\Error\ConcurrentModificationException
137
     * @throws \Commercetools\Core\Error\ErrorResponseException
138
     * @throws \Commercetools\Core\Error\GatewayTimeoutException
139
     * @throws \Commercetools\Core\Error\InternalServerErrorException
140
     * @throws \Commercetools\Core\Error\InvalidTokenException
141
     * @throws \Commercetools\Core\Error\NotFoundException
142
     * @throws \Commercetools\Core\Error\ServiceUnavailableException
143
     */
144
    public function executeBatch(array $requests)
145
    {
146
        $results = Pool::batch(
147
            $this->client,
148
            $this->getBatchHttpRequests($requests)
149
        );
150
151
        $responses = [];
152
        foreach ($results as $key => $result) {
153
            if (!$result instanceof RequestException) {
154
                $response = $this->packResponse($result);
155 View Code Duplication
            } else {
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...
156
                $httpResponse = $this->packResponse($result->getResponse());
0 ignored issues
show
Bug introduced by
It seems like $result->getResponse() targeting GuzzleHttp\Exception\Req...xception::getResponse() can also be of type object<Psr\Http\Message\ResponseInterface>; however, Commercetools\Core\Clien...Adapter::packResponse() does only seem to accept null|object<GuzzleHttp\Message\ResponseInterface>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
157
                $request = $requests[$key];
158
                $response = ApiException::create($request, $httpResponse, $result);
159
            }
160
            $responses[$key] = $response;
161
        }
162
163
        return $responses;
164
    }
165
166
    /**
167
     * @return array
168
     */
169
    protected function getBatchHttpRequests(array $requests)
170
    {
171
        $requests = array_map(
172
            function ($request) {
173
                /**
174
                 * @var RequestInterface $request
175
                 */
176
                return $this->client->createRequest(
0 ignored issues
show
Bug introduced by
The method createRequest() does not exist on GuzzleHttp\Client. Did you maybe mean request()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
177
                    $request->getMethod(),
178
                    (string)$request->getUri(),
179
                    ['headers' => $request->getHeaders()]
180
                );
181
            },
182
            $requests
183
        );
184
185
        return $requests;
186
    }
187
188
    /**
189
     * @param $oauthUri
190
     * @param $clientId
191
     * @param $clientSecret
192
     * @param $formParams
193
     * @return ResponseInterface
194
     */
195
    public function authenticate($oauthUri, $clientId, $clientSecret, $formParams)
196
    {
197
        $options = [
198
            'body' => $formParams,
199
            'auth' => [$clientId, $clientSecret]
200
        ];
201
202
        try {
203
            $response = $this->client->post($oauthUri, $options);
204
        } catch (RequestException $exception) {
205
            $authRequest = $exception->getRequest();
206
            $request = new Request(
207
                $authRequest->getMethod(),
208
                $authRequest->getUrl(),
0 ignored issues
show
Bug introduced by
The method getUrl() does not seem to exist on object<Psr\Http\Message\RequestInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
209
                $authRequest->getHeaders(),
210
                (string)$authRequest->getBody()
211
            );
212
            $response = $this->packResponse($exception->getResponse());
0 ignored issues
show
Bug introduced by
It seems like $exception->getResponse() targeting GuzzleHttp\Exception\Req...xception::getResponse() can also be of type object<Psr\Http\Message\ResponseInterface>; however, Commercetools\Core\Clien...Adapter::packResponse() does only seem to accept null|object<GuzzleHttp\Message\ResponseInterface>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
213
            throw ApiException::create($request, $response, $exception);
214
        }
215
        return $response;
216
    }
217
218
    /**
219
     * @param RequestInterface $request
220
     * @return AdapterPromiseInterface
221
     */
222
    public function executeAsync(RequestInterface $request)
223
    {
224
        $options = [
225
            'future' => true,
226
            'exceptions' => false,
227
            'headers' => $request->getHeaders()
228
        ];
229
        $request = $this->client->createRequest($request->getMethod(), (string)$request->getUri(), $options);
0 ignored issues
show
Bug introduced by
The method createRequest() does not exist on GuzzleHttp\Client. Did you maybe mean request()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
230
        $guzzlePromise = $this->client->send($request, $options);
231
232
        $promise = new Guzzle5Promise($guzzlePromise);
0 ignored issues
show
Documentation introduced by
$guzzlePromise is of type object<Psr\Http\Message\ResponseInterface>, but the function expects a object<GuzzleHttp\Message\FutureResponse>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
233
        $promise->then(
234
            function (\GuzzleHttp\Message\ResponseInterface $response) {
235
                return new Response(
236
                    $response->getStatusCode(),
237
                    $response->getHeaders(),
238
                    (string)$response->getBody(),
239
                    $response->getProtocolVersion(),
240
                    $response->getReasonPhrase()
241
                );
242
            }
243
        );
244
245
        return $promise;
246
    }
247
248
    public static function getAdapterInfo()
249
    {
250
        return 'GuzzleHttp/' . Client::VERSION;
251
    }
252
}
253