Completed
Push — master ( 9c37c7...1d2d63 )
by Jens
08:02
created

Guzzle5Adapter::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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