1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
/** |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace CommerceLeague\ActiveCampaignApi\Client; |
7
|
|
|
|
8
|
|
|
use Psr\Http\Client\ClientInterface; |
9
|
|
|
use Psr\Http\Message\RequestFactoryInterface; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
use Psr\Http\Message\StreamFactoryInterface; |
12
|
|
|
use Psr\Http\Message\StreamInterface; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Class HttpClient |
16
|
|
|
*/ |
17
|
|
|
class HttpClient implements HttpClientInterface |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var ClientInterface |
21
|
|
|
*/ |
22
|
|
|
protected $baseHttpClient; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var RequestFactoryInterface |
26
|
|
|
*/ |
27
|
|
|
protected $requestFactory; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var HttpExceptionHandler |
31
|
|
|
*/ |
32
|
|
|
protected $httpExceptionHandler; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var StreamFactoryInterface |
36
|
|
|
*/ |
37
|
|
|
private $streamFactory; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param ClientInterface $baseHttpClient |
41
|
|
|
* @param RequestFactoryInterface $requestFactory |
42
|
|
|
* @param StreamFactoryInterface $streamFactory |
43
|
|
|
*/ |
44
|
|
|
public function __construct( |
45
|
|
|
ClientInterface $baseHttpClient, |
46
|
|
|
RequestFactoryInterface $requestFactory, |
47
|
|
|
StreamFactoryInterface $streamFactory |
48
|
|
|
) { |
49
|
|
|
$this->baseHttpClient = $baseHttpClient; |
50
|
|
|
$this->requestFactory = $requestFactory; |
51
|
|
|
$this->streamFactory = $streamFactory; |
52
|
|
|
$this->httpExceptionHandler = new HttpExceptionHandler(); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @inheritDoc |
57
|
|
|
*/ |
58
|
|
|
public function sendRequest(string $httpMethod, $uri, array $headers = [], $body = null): ResponseInterface |
59
|
|
|
{ |
60
|
|
|
$request = $this->requestFactory->createRequest($httpMethod, $uri); |
61
|
|
|
|
62
|
|
|
if ($body !== null && is_string($body)) { |
63
|
|
|
$request = $request->withBody($this->streamFactory->createStream($body)); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
if ($body !== null && $body instanceof StreamInterface) { |
67
|
|
|
$request = $request->withBody($body); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
foreach ($headers as $header => $content) { |
71
|
|
|
$request = $request->withHeader($header, $content); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$response = $this->baseHttpClient->sendRequest($request); |
75
|
|
|
$response = $this->httpExceptionHandler->transformResponseToException($request, $response); |
76
|
|
|
|
77
|
|
|
return $response; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|