1+ <?php
2+
3+ namespace Kelunik \Http \Adapter \Artax ;
4+
5+ use Amp \Artax ;
6+ use Amp \Promise ;
7+ use Http \Client \Exception \RequestException ;
8+ use Http \Client \HttpClient ;
9+ use Http \Discovery \MessageFactoryDiscovery ;
10+ use Http \Discovery \StreamFactoryDiscovery ;
11+ use Http \Message \ResponseFactory ;
12+ use Http \Message \StreamFactory ;
13+ use Psr \Http \Message \RequestInterface ;
14+ use function Amp \call ;
15+
16+ class Client implements HttpClient {
17+ private $ client ;
18+ private $ responseFactory ;
19+ private $ streamFactory ;
20+
21+ public function __construct (Artax \Client $ client = null , ResponseFactory $ responseFactory = null , StreamFactory $ streamFactory = null ) {
22+ $ this ->client = $ client ?? new Artax \DefaultClient ;
23+ $ this ->responseFactory = $ responseFactory ?? MessageFactoryDiscovery::find ();
24+ $ this ->streamFactory = $ streamFactory ?? StreamFactoryDiscovery::find ();
25+ }
26+
27+ /** @inheritdoc */
28+ public function sendRequest (RequestInterface $ request ) {
29+ return Promise \wait (call (function () use ($ request ) {
30+ /** @var Artax\Request $req */
31+ $ req = new Artax \Request ($ request ->getUri (), $ request ->getMethod ());
32+ $ req = $ req ->withProtocolVersions ([$ request ->getProtocolVersion ()]);
33+ $ req = $ req ->withHeaders ($ request ->getHeaders ());
34+ $ req = $ req ->withBody ((string ) $ request ->getBody ());
35+
36+ try {
37+ /** @var Artax\Response $resp */
38+ $ resp = yield $ this ->client ->request ($ req , [
39+ Artax \Client::OP_MAX_REDIRECTS => 0 ,
40+ ]);
41+ } catch (Artax \HttpException $ e ) {
42+ throw new RequestException ($ e ->getMessage (), $ request , $ e );
43+ }
44+
45+ $ respBody = $ resp ->getBody ();
46+ $ bodyStream = $ this ->streamFactory ->createStream ();
47+
48+ while (null !== $ chunk = yield $ respBody ->read ()) {
49+ $ bodyStream ->write ($ chunk );
50+ }
51+
52+ $ bodyStream ->rewind ();
53+
54+ return $ this ->responseFactory ->createResponse (
55+ $ resp ->getStatus (),
56+ $ resp ->getReason (),
57+ $ resp ->getHeaders (),
58+ $ bodyStream ,
59+ $ resp ->getProtocolVersion ()
60+ );
61+ }));
62+ }
63+ }
0 commit comments