|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bokbasen\ApiClient; |
|
4
|
|
|
|
|
5
|
|
|
use Bokbasen\ApiClient\Exceptions\BokbasenApiClientException; |
|
6
|
|
|
use Http\Client\HttpClient; |
|
7
|
|
|
use Http\Discovery\HttpClientDiscovery; |
|
8
|
|
|
use Http\Discovery\MessageFactoryDiscovery; |
|
9
|
|
|
use Http\Message\MessageFactory; |
|
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
11
|
|
|
use Psr\Http\Message\StreamInterface; |
|
12
|
|
|
use Psr\Http\Message\UriInterface; |
|
13
|
|
|
|
|
14
|
|
|
class Caller |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @var HttpClient |
|
18
|
|
|
*/ |
|
19
|
|
|
private $httpClient; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var MessageFactory |
|
23
|
|
|
*/ |
|
24
|
|
|
private $messageFactory; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @param string $method |
|
28
|
|
|
* @param string|UriInterface $url |
|
29
|
|
|
* @param array $headers |
|
30
|
|
|
* @param resource|string|StreamInterface|null $body |
|
31
|
|
|
* |
|
32
|
|
|
* @return ResponseInterface |
|
33
|
|
|
* |
|
34
|
|
|
* @throws BokbasenApiClientException |
|
35
|
|
|
*/ |
|
36
|
2 |
|
public function request(string $method, $url, array $headers = [], $body = null): ResponseInterface |
|
37
|
|
|
{ |
|
38
|
|
|
try { |
|
39
|
2 |
|
return $this->getHttpClient()->sendRequest( |
|
40
|
|
|
$this->getMessageFactory()->createRequest($method, $url, $headers, $body) |
|
41
|
|
|
); |
|
42
|
2 |
|
} catch (\Http\Client\Exception | \Exception $e) { |
|
43
|
2 |
|
throw new BokbasenApiClientException($e->getMessage(), $e->getCode(), $e); |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
2 |
|
protected function getHttpClient(HttpClient $httpClient = null): HttpClient |
|
48
|
|
|
{ |
|
49
|
2 |
|
if (!$this->httpClient) { |
|
50
|
2 |
|
$this->httpClient = $httpClient ?: HttpClientDiscovery::find(); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
return $this->httpClient; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
protected function getMessageFactory(MessageFactory $messageFactory = null): MessageFactory |
|
57
|
|
|
{ |
|
58
|
|
|
if (!$this->messageFactory) { |
|
59
|
|
|
$this->messageFactory = $messageFactory ?: MessageFactoryDiscovery::find(); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
return $this->messageFactory; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|