Completed
Push — master ( 18bfc7...82e0b5 )
by Jens
18:00 queued 05:19
created

Guzzle5Adapter::getAdapterInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * @author @jayS-de <[email protected]>
4
 */
5
6
namespace Commercetools\Core\Client\Adapter;
7
8
use GuzzleHttp\Client;
9
use GuzzleHttp\Exception\RequestException;
10
use GuzzleHttp\Pool;
11
use GuzzleHttp\Psr7\Request;
12
use GuzzleHttp\Psr7\Response;
13
use GuzzleHttp\Subscriber\Log\LogSubscriber;
14
use Psr\Http\Message\RequestInterface;
15
use Psr\Http\Message\ResponseInterface;
16
use Psr\Log\LoggerInterface;
17
use Commercetools\Core\Error\ApiException;
18
19
class Guzzle5Adapter implements AdapterInterface
20
{
21
    /**
22
     * @var Client
23
     */
24
    protected $client;
25
26
    /**
27
     * @var LoggerInterface
28
     */
29
    protected $logger;
30
31
    /**
32
     * @param array $options
33
     */
34
    public function __construct(array $options = [])
35
    {
36
        if (isset($options['base_uri'])) {
37
            $options['base_url'] = $options['base_uri'];
38
            unset($options['base_uri']);
39
        }
40
        if (isset($options['headers'])) {
41
            $options['defaults']['headers'] = $options['headers'];
42
            unset($options['headers']);
43
        }
44
        $options = array_merge(
45
            [
46
                'allow_redirects' => false,
47
                'verify' => true,
48
                'timeout' => 60,
49
                'connect_timeout' => 10,
50
                'pool_size' => 25
51
            ],
52
            $options
53
        );
54
        $this->client = new Client($options);
55
    }
56
57
    public function setLogger(LoggerInterface $logger)
58
    {
59
        $this->logger = $logger;
60
        if ($logger instanceof LoggerInterface) {
61
            $this->getEmitter()->attach(new LogSubscriber($logger));
62
        }
63
    }
64
65
    public function addHandler($handler)
66
    {
67
        $this->getEmitter()->attach($handler);
68
    }
69
70
    /**
71
     * @internal
72
     * @return \GuzzleHttp\Event\Emitter|\GuzzleHttp\Event\EmitterInterface
73
     */
74
    public function getEmitter()
75
    {
76
        return $this->client->getEmitter();
77
    }
78
79
    /**
80
     * @param RequestInterface $request
81
     * @return ResponseInterface
82
     * @throws \Commercetools\Core\Error\ApiException
83
     * @throws \Commercetools\Core\Error\BadGatewayException
84
     * @throws \Commercetools\Core\Error\ConcurrentModificationException
85
     * @throws \Commercetools\Core\Error\ErrorResponseException
86
     * @throws \Commercetools\Core\Error\GatewayTimeoutException
87
     * @throws \Commercetools\Core\Error\InternalServerErrorException
88
     * @throws \Commercetools\Core\Error\InvalidTokenException
89
     * @throws \Commercetools\Core\Error\NotFoundException
90
     * @throws \Commercetools\Core\Error\ServiceUnavailableException
91
     */
92
    public function execute(RequestInterface $request)
93
    {
94
        $options = [
95
            'headers' => $request->getHeaders(),
96
            'body' => (string)$request->getBody()
97
        ];
98
99
        try {
100
            $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...
101
            $guzzleResponse = $this->client->send($guzzleRequest);
102
            $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...
103
        } catch (RequestException $exception) {
104
            $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...
105
            throw ApiException::create($request, $response, $exception);
106
        }
107
108
        return $response;
109
    }
110
111
    protected function packResponse(\GuzzleHttp\Message\ResponseInterface $response = null)
112
    {
113
        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...
114
            return null;
115
        }
116
        return new Response(
117
            $response->getStatusCode(),
118
            $response->getHeaders(),
119
            (string)$response->getBody()
120
        );
121
    }
122
123
    /**
124
     * @param RequestInterface[] $requests
125
     * @return \Psr\Http\Message\ResponseInterface[]
126
     * @throws \Commercetools\Core\Error\ApiException
127
     * @throws \Commercetools\Core\Error\BadGatewayException
128
     * @throws \Commercetools\Core\Error\ConcurrentModificationException
129
     * @throws \Commercetools\Core\Error\ErrorResponseException
130
     * @throws \Commercetools\Core\Error\GatewayTimeoutException
131
     * @throws \Commercetools\Core\Error\InternalServerErrorException
132
     * @throws \Commercetools\Core\Error\InvalidTokenException
133
     * @throws \Commercetools\Core\Error\NotFoundException
134
     * @throws \Commercetools\Core\Error\ServiceUnavailableException
135
     */
136
    public function executeBatch(array $requests)
137
    {
138
        $results = Pool::batch(
139
            $this->client,
140
            $this->getBatchHttpRequests($requests)
141
        );
142
143
        $responses = [];
144
        foreach ($results as $key => $result) {
145
            if (!$result instanceof RequestException) {
146
                $response = $this->packResponse($result);
147 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...
148
                $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...
149
                $request = $requests[$key];
150
                $response = ApiException::create($request, $httpResponse, $result);
151
            }
152
            $responses[$key] = $response;
153
        }
154
155
        return $responses;
156
    }
157
158
    /**
159
     * @return array
160
     */
161
    protected function getBatchHttpRequests(array $requests)
162
    {
163
        $requests = array_map(
164
            function ($request) {
165
                /**
166
                 * @var RequestInterface $request
167
                 */
168
                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...
169
                    $request->getMethod(),
170
                    (string)$request->getUri(),
171
                    ['headers' => $request->getHeaders()]
172
                );
173
            },
174
            $requests
175
        );
176
177
        return $requests;
178
    }
179
180
    /**
181
     * @param $oauthUri
182
     * @param $clientId
183
     * @param $clientSecret
184
     * @param $formParams
185
     * @return ResponseInterface
186
     */
187
    public function authenticate($oauthUri, $clientId, $clientSecret, $formParams)
188
    {
189
        $options = [
190
            'body' => $formParams,
191
            'auth' => [$clientId, $clientSecret]
192
        ];
193
194
        try {
195
            $response = $this->client->post($oauthUri, $options);
196
        } catch (RequestException $exception) {
197
            $authRequest = $exception->getRequest();
198
            $request = new Request(
199
                $authRequest->getMethod(),
200
                $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...
201
                $authRequest->getHeaders(),
202
                (string)$authRequest->getBody()
203
            );
204
            $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...
205
            throw ApiException::create($request, $response, $exception);
206
        }
207
        return $response;
208
    }
209
210
    /**
211
     * @param RequestInterface $request
212
     * @return AdapterPromiseInterface
213
     */
214
    public function executeAsync(RequestInterface $request)
215
    {
216
        $options = [
217
            'future' => true,
218
            'exceptions' => false,
219
            'headers' => $request->getHeaders()
220
        ];
221
        $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...
222
        $guzzlePromise = $this->client->send($request, $options);
223
224
        $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...
225
        $promise->then(
226
            function (\GuzzleHttp\Message\ResponseInterface $response) {
227
                return new Response(
228
                    $response->getStatusCode(),
229
                    $response->getHeaders(),
230
                    (string)$response->getBody(),
231
                    $response->getProtocolVersion(),
232
                    $response->getReasonPhrase()
233
                );
234
            }
235
        );
236
237
        return $promise;
238
    }
239
240
    public static function getAdapterInfo()
241
    {
242
        return 'GuzzleHttp/' . Client::VERSION;
243
    }
244
}
245