1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bokbasen\ApiClient; |
4
|
|
|
|
5
|
|
|
use Bokbasen\ApiClient\Exceptions\BokbasenApiClientException; |
6
|
|
|
use Http\Discovery\Psr17FactoryDiscovery; |
7
|
|
|
use Http\Discovery\Psr18ClientDiscovery; |
8
|
|
|
use Psr\Http\Client\ClientExceptionInterface; |
9
|
|
|
use Psr\Http\Client\ClientInterface; |
10
|
|
|
use Psr\Http\Message\RequestFactoryInterface; |
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
12
|
|
|
use Psr\Http\Message\StreamFactoryInterface; |
13
|
|
|
use Psr\Http\Message\StreamInterface; |
14
|
|
|
use Psr\Http\Message\UriInterface; |
15
|
|
|
|
16
|
|
|
class Caller |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var ClientInterface |
20
|
|
|
*/ |
21
|
|
|
private $httpClient; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var RequestFactoryInterface |
25
|
|
|
*/ |
26
|
|
|
private $requestFactory; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var StreamFactoryInterface |
30
|
|
|
*/ |
31
|
|
|
private $streamFactory; |
32
|
|
|
|
33
|
24 |
|
public function __construct( |
34
|
|
|
ClientInterface $httpClient = null, |
35
|
|
|
RequestFactoryInterface $requestFactory = null, |
36
|
|
|
StreamFactoryInterface $streamFactory = null |
37
|
|
|
) { |
38
|
24 |
|
$this->httpClient = $httpClient ?: Psr18ClientDiscovery::find(); |
39
|
24 |
|
$this->requestFactory = $requestFactory ?: Psr17FactoryDiscovery::findRequestFactory(); |
40
|
24 |
|
$this->streamFactory = $streamFactory ?: Psr17FactoryDiscovery::findStreamFactory(); |
41
|
24 |
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param string $method |
45
|
|
|
* @param string|UriInterface $url |
46
|
|
|
* @param array $headers |
47
|
|
|
* @param string|StreamInterface|null $body |
48
|
|
|
* |
49
|
|
|
* @return ResponseInterface |
50
|
|
|
* |
51
|
|
|
* @throws BokbasenApiClientException |
52
|
|
|
*/ |
53
|
24 |
|
public function request(string $method, $url, array $headers = [], $body = null): ResponseInterface |
54
|
|
|
{ |
55
|
|
|
try { |
56
|
24 |
|
$request = $this->requestFactory->createRequest($method, $url); |
57
|
|
|
|
58
|
24 |
|
if (!empty($headers)) { |
59
|
21 |
|
foreach ($headers as $name => $value) { |
60
|
21 |
|
$request = $request->withHeader($name, $value); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
24 |
|
if ($body !== null) { |
65
|
15 |
|
$request = $request->withBody( |
66
|
15 |
|
$this->streamFactory->createStream($body) |
67
|
|
|
); |
68
|
|
|
} |
69
|
|
|
|
70
|
24 |
|
return $this->httpClient->sendRequest($request); |
71
|
3 |
|
} catch (ClientExceptionInterface | \Exception $e) { |
72
|
3 |
|
throw new BokbasenApiClientException($e->getMessage(), $e->getCode(), $e); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
21 |
|
public function setHttpClient(ClientInterface $httpClient): void |
77
|
|
|
{ |
78
|
21 |
|
$this->httpClient = $httpClient; |
79
|
21 |
|
} |
80
|
|
|
} |
81
|
|
|
|