1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Mikemirten\Component\JsonApi\HttpClient\Adapter; |
5
|
|
|
|
6
|
|
|
use GuzzleHttp\ClientInterface as GuzzleClientInterface; |
7
|
|
|
use GuzzleHttp\Exception\RequestException as GuzzleRequestException; |
8
|
|
|
use GuzzleHttp\Exception\BadResponseException as GuzzleResponseException; |
9
|
|
|
use Mikemirten\Component\JsonApi\HttpClient\Exception\RequestException; |
10
|
|
|
use Mikemirten\Component\JsonApi\HttpClient\Exception\ResponseException; |
11
|
|
|
use Mikemirten\Component\JsonApi\HttpClient\HttpClientInterface; |
12
|
|
|
use Psr\Http\Message\RequestInterface; |
13
|
|
|
use Psr\Http\Message\ResponseInterface; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Guzzle HTTP Client adapter |
17
|
|
|
* |
18
|
|
|
* @package Mikemirten\Component\JsonApi\HttpClient |
19
|
|
|
*/ |
20
|
|
|
class GuzzleAdapter implements HttpClientInterface |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var GuzzleClientInterface |
24
|
|
|
*/ |
25
|
|
|
protected $client; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* GuzzleAdapter constructor. |
29
|
|
|
* |
30
|
|
|
* @param GuzzleClientInterface $client |
31
|
|
|
*/ |
32
|
3 |
|
public function __construct(GuzzleClientInterface $client) |
33
|
|
|
{ |
34
|
3 |
|
$this->client = $client; |
35
|
3 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* {@inheritdoc} |
39
|
|
|
*/ |
40
|
3 |
|
public function request(RequestInterface $request): ResponseInterface |
41
|
|
|
{ |
42
|
|
|
try { |
43
|
3 |
|
return $this->client->send($request); |
44
|
|
|
} |
45
|
2 |
|
catch (GuzzleRequestException $exception) { |
46
|
2 |
|
throw $this->createException($exception); |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Create HTTP-Client RequestException by a Guzzle exception |
52
|
|
|
* |
53
|
|
|
* @param GuzzleRequestException $exception |
54
|
|
|
* @return RequestException |
55
|
|
|
*/ |
56
|
2 |
|
protected function createException(GuzzleRequestException $exception): RequestException |
57
|
|
|
{ |
58
|
2 |
|
if ($exception instanceof GuzzleResponseException) { |
59
|
1 |
|
return new ResponseException( |
60
|
1 |
|
$exception->getRequest(), |
61
|
1 |
|
$exception->getResponse(), |
|
|
|
|
62
|
1 |
|
$exception |
63
|
|
|
); |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
throw new RequestException( |
67
|
1 |
|
$exception->getRequest(), |
68
|
1 |
|
$exception |
69
|
|
|
); |
70
|
|
|
} |
71
|
|
|
} |
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: