Completed
Branch add-psr-18-support (ba8bb1)
by Steven
02:27
created

Http::getRequestExceptionParts()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 8.9617
c 0
b 0
f 0
cc 6
nc 32
nop 1
1
<?php
2
3
namespace Stevenmaguire\Services\Trello;
4
5
use Exception;
6
use Psr\Http\Client\ClientExceptionInterface;
7
use Psr\Http\Client\ClientInterface;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\RequestFactoryInterface;
10
use Psr\Http\Message\StreamFactoryInterface;
11
12
class Http
13
{
14
    const HTTP_DELETE = 'DELETE';
15
    const HTTP_GET = 'GET';
16
    const HTTP_POST = 'POST';
17
    const HTTP_PUT = 'PUT';
18
19
    /**
20
     * Multipart resources to include in next request.
21
     *
22
     * @var array
23
     */
24
    protected $multipartResources = [];
25
26
    /**
27
     * Http client
28
     *
29
     * @var ClientInterface
30
     */
31
    protected $httpClient;
32
33
    /**
34
     * Http request factory
35
     *
36
     * @var RequestFactoryInterface
37
     */
38
    protected $httpRequestFactory;
39
40
    /**
41
     * Http stream factory
42
     *
43
     * @var StreamFactoryInterface
44
     */
45
    protected $httpStreamFactory;
46
47
    /**
48
     * Creates a new http broker.
49
     */
50
    public function __construct()
51
    {
52
        //
53
    }
54
55
    /**
56
     * Adds authentication credentials to given request.
57
     *
58
     * @param  RequestInterface  $request
59
     *
60
     * @return RequestInterface
61
     */
62
    protected function authenticateRequest(RequestInterface $request)
63
    {
64
        $uri = $request->getUri();
65
        parse_str($uri->getQuery(), $query);
66
67
        $query['key'] = Configuration::get('key');
68
        $query['token'] = Configuration::get('token');
69
70
        $uri = $uri->withQuery(http_build_query($query));
71
72
        return $request->withUri($uri);
73
    }
74
75
    /**
76
     * Creates a request.
77
     *
78
     * @param  string $verb
79
     * @param  string $path
80
     * @param  array  $parameters
81
     *
82
     * @return RequestInterface
83
     */
84
    protected function createRequest($verb, $path, $parameters = [])
85
    {
86
        if (isset($parameters['file'])) {
87
            $this->queueResourceAs(
88
                'file',
89
                $this->httpStreamFactory->createStreamFromResource($parameters['file'])
0 ignored issues
show
Documentation introduced by
$this->httpStreamFactory...ce($parameters['file']) is of type object<Psr\Http\Message\StreamInterface>, but the function expects a object<Stevenmaguire\Ser...essage\StreamInterface>.

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...
90
            );
91
            unset($parameters['file']);
92
        }
93
94
        $request = $this->httpRequestFactory->createRequest(
95
            $verb,
96
            $this->getUrlFromPath($path)
97
        );
98
99
        $headers = $this->getHeaders();
100
101
        array_walk($headers, function ($value, $key) use (&$request) {
102
            $request = $request->withHeader($key, $value);
103
        });
104
105
        return $request->withUri(
106
            $request->getUri()->withQuery(
107
                http_build_query($parameters)
108
            )
109
        );
110
    }
111
112
    /**
113
     * Retrieves http response for a request with the delete method.
114
     *
115
     * @param  string $path
116
     * @param  array  $parameters
117
     *
118
     * @return object
119
     */
120
    public function delete($path, $parameters = [])
121
    {
122
        $request = $this->getRequest(static::HTTP_DELETE, $path, $parameters);
123
124
        return $this->sendRequest($request);
125
    }
126
127
    /**
128
     * Retrieves http response for a request with the get method.
129
     *
130
     * @param  string $path
131
     * @param  array  $parameters
132
     *
133
     * @return object
134
     */
135
    public function get($path, $parameters = [])
136
    {
137
        $request = $this->getRequest(static::HTTP_GET, $path, $parameters);
138
139
        return $this->sendRequest($request);
140
    }
141
142
    /**
143
     * Creates and returns a request.
144
     *
145
     * @param  string $method
146
     * @param  string $path
147
     * @param  array  $parameters
148
     *
149
     * @return RequestInterface
150
     */
151
    public function getRequest($method, $path, $parameters = [], $authenticated = true)
152
    {
153
        $request = $this->createRequest($method, $path, $parameters);
154
155
        if ($authenticated) {
156
            $request = $this->authenticateRequest($request);
157
        }
158
159
        return $request;
160
    }
161
162
    /**
163
     * Retrieves default headers.
164
     *
165
     * @return array
166
     */
167
    protected function getHeaders()
168
    {
169
        return ['accept' => 'application/json'];
170
    }
171
172
    /**
173
     * Creates an array of request options based on the current status of the
174
     * http client.
175
     *
176
     * @return array
177
     */
178
    protected function getRequestOptions()
179
    {
180
        $options = [
181
            'proxy' => Configuration::get('proxy')
182
        ];
183
184
        if (!empty(array_filter($this->multipartResources))) {
185
            $options['multipart'] = $this->multipartResources;
186
        }
187
188
        return $options;
189
    }
190
191
    /**
192
     * Creates fully qualified domain from given path.
193
     *
194
     * @param  string  $path
195
     *
196
     * @return string
197
     */
198
    public function getUrlFromPath($path = '/')
199
    {
200
        return Configuration::get('domain').'/'.Configuration::get('version').'/'.ltrim($path, '/');
201
    }
202
203
    /**
204
     * Retrieves http response for a request with the post method.
205
     *
206
     * @param  string $path
207
     * @param  array  $parameters
208
     *
209
     * @return object
210
     */
211
    public function post($path, $parameters)
212
    {
213
        $request = $this->getRequest(static::HTTP_POST, $path, $parameters);
214
215
        return $this->sendRequest($request);
216
    }
217
218
    /**
219
     * Retrieves http response for a request with the put method.
220
     *
221
     * @param  string $path
222
     * @param  array  $parameters
223
     *
224
     * @return object
225
     */
226
    public function put($path, $parameters)
227
    {
228
        $request = $this->getRequest(static::HTTP_PUT, $path, $parameters);
229
230
        return $this->sendRequest($request);
231
    }
232
233
    /**
234
     * Retrieves http response for a request with the put method,
235
     * ensuring parameters are passed as body.
236
     *
237
     * @param  string $path
238
     * @param  array  $parameters
239
     *
240
     * @return object
241
     */
242
    public function putAsBody($path, $parameters)
243
    {
244
        $request = $this->getRequest(static::HTTP_PUT, $path)
245
            ->withBody($this->httpStreamFactory->createStream(json_encode($parameters)))
246
            ->withHeader('content-type', 'application/json');
247
248
        return $this->sendRequest($request);
249
    }
250
251
    /**
252
     * Adds a given resource to multipart stream collection, to be processed by next request.
253
     *
254
     * @param  string                           $name
255
     * @param  Psr\Http\Message\StreamInterface $resource
256
     *
257
     * @return void
258
     */
259
    protected function queueResourceAs($name, $resource)
260
    {
261
        array_push($this->multipartResources, [
262
            'name' => $name,
263
            'contents' => $resource,
264
        ]);
265
    }
266
267
    /**
268
     * Retrieves http response for a given request.
269
     *
270
     * @param  RequestInterface $request
271
     *
272
     * @return object
273
     * @throws Exceptions\Exception
274
     */
275
    protected function sendRequest(RequestInterface $request)
276
    {
277
        try {
278
            $options = $this->getRequestOptions();
0 ignored issues
show
Unused Code introduced by
$options is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
279
            $response = $this->httpClient->sendRequest($request/*, $options*/);
280
281
            $this->multipartResources = [];
282
283
            return json_decode($response->getBody());
284
        } catch (ClientExceptionInterface $e) {
285
            throw Exceptions\Exception::fromClientException($e);
286
        }
287
    } // @codeCoverageIgnore
288
289
    /**
290
     * Updates the http client.
291
     *
292
     * @param ClientInterface  $httpClient
293
     *
294
     * @return Http
295
     */
296
    public function setClient(ClientInterface $httpClient)
297
    {
298
        $this->httpClient = $httpClient;
299
300
        return $this;
301
    }
302
303
    /**
304
     * Updates the http request factory.
305
     *
306
     * @param RequestFactoryInterface  $httpRequestFactory
307
     *
308
     * @return Http
309
     */
310
    public function setRequestFactory(RequestFactoryInterface $httpRequestFactory)
311
    {
312
        $this->httpRequestFactory = $httpRequestFactory;
313
314
        return $this;
315
    }
316
317
    /**
318
     * Updates the http stream factory.
319
     *
320
     * @param StreamFactoryInterface  $httpStreamFactory
321
     *
322
     * @return Http
323
     */
324
    public function setStreamFactory(StreamFactoryInterface $httpStreamFactory)
325
    {
326
        $this->httpStreamFactory = $httpStreamFactory;
327
328
        return $this;
329
    }
330
}
331