-
Notifications
You must be signed in to change notification settings - Fork 0
/
Psr18ClientAdapter.php
72 lines (59 loc) · 1.99 KB
/
Psr18ClientAdapter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
namespace Marein\Nchan\HttpAdapter;
use Marein\Nchan\Exception\NchanException;
use Marein\Nchan\Http\Client;
use Marein\Nchan\Http\Request;
use Marein\Nchan\Http\Response;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
final class Psr18ClientAdapter implements Client
{
private ClientInterface $client;
private RequestFactoryInterface $requestFactory;
private StreamFactoryInterface $streamFactory;
public function __construct(
ClientInterface $client,
RequestFactoryInterface $requestFactory,
StreamFactoryInterface $streamFactory
) {
$this->client = $client;
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;
}
public function get(Request $request): Response
{
return $this->request('GET', $request);
}
public function post(Request $request): Response
{
return $this->request('POST', $request);
}
public function delete(Request $request): Response
{
return $this->request('DELETE', $request);
}
/**
* @throws NchanException
*/
private function request(string $method, Request $request): Response
{
try {
$psrRequest = $this->requestFactory
->createRequest($method, $request->url()->toString())
->withBody($this->streamFactory->createStream($request->body()));
foreach ($request->headers() as $name => $value) {
$psrRequest = $psrRequest->withHeader($name, $value);
}
return new Psr7ResponseAdapter($this->client->sendRequest($psrRequest));
} catch (ClientExceptionInterface $exception) {
throw new NchanException(
$exception->getMessage(),
$exception->getCode(),
$exception
);
}
}
}