|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Http\Adapter\Guzzle6; |
|
6
|
|
|
|
|
7
|
|
|
use GuzzleHttp\Client as GuzzleClient; |
|
8
|
|
|
use GuzzleHttp\ClientInterface; |
|
9
|
|
|
use GuzzleHttp\HandlerStack; |
|
10
|
|
|
use GuzzleHttp\Middleware; |
|
11
|
|
|
use Http\Client\HttpAsyncClient; |
|
12
|
|
|
use Http\Client\HttpClient; |
|
13
|
|
|
use Psr\Http\Message\RequestInterface; |
|
14
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* HTTP Adapter for Guzzle 6. |
|
18
|
|
|
* |
|
19
|
|
|
* @author David de Boer <[email protected]> |
|
20
|
|
|
*/ |
|
21
|
|
|
final class Client implements HttpClient, HttpAsyncClient |
|
22
|
|
|
{ |
|
23
|
|
|
/** |
|
24
|
|
|
* @var ClientInterface |
|
25
|
|
|
*/ |
|
26
|
|
|
private $client; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* If you pass a Guzzle instance as $client, make sure to configure Guzzle to not |
|
30
|
|
|
* throw exceptions on HTTP error status codes, or this adapter will violate PSR-18. |
|
31
|
|
|
* See also self::buildClient at the bottom of this class. |
|
32
|
|
|
*/ |
|
33
|
363 |
|
public function __construct(?ClientInterface $client = null) |
|
34
|
|
|
{ |
|
35
|
363 |
|
if (!$client) { |
|
36
|
51 |
|
$client = self::buildClient(); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
363 |
|
$this->client = $client; |
|
40
|
363 |
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Factory method to create the Guzzle 6 adapter with custom Guzzle configuration. |
|
44
|
|
|
*/ |
|
45
|
|
|
public static function createWithConfig(array $config): Client |
|
46
|
|
|
{ |
|
47
|
|
|
return new self(self::buildClient($config)); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* {@inheritdoc} |
|
52
|
|
|
*/ |
|
53
|
204 |
|
public function sendRequest(RequestInterface $request): ResponseInterface |
|
54
|
|
|
{ |
|
55
|
204 |
|
$promise = $this->sendAsyncRequest($request); |
|
56
|
|
|
|
|
57
|
204 |
|
return $promise->wait(); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* {@inheritdoc} |
|
62
|
|
|
*/ |
|
63
|
363 |
|
public function sendAsyncRequest(RequestInterface $request) |
|
64
|
|
|
{ |
|
65
|
363 |
|
$promise = $this->client->sendAsync($request); |
|
66
|
|
|
|
|
67
|
363 |
|
return new Promise($promise, $request); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* Build the Guzzle client instance. |
|
72
|
|
|
*/ |
|
73
|
51 |
|
private static function buildClient(array $config = []): GuzzleClient |
|
74
|
|
|
{ |
|
75
|
51 |
|
$handlerStack = new HandlerStack(\GuzzleHttp\choose_handler()); |
|
76
|
51 |
|
$handlerStack->push(Middleware::prepareBody(), 'prepare_body'); |
|
77
|
51 |
|
$config = array_merge(['handler' => $handlerStack], $config); |
|
78
|
|
|
|
|
79
|
51 |
|
return new GuzzleClient($config); |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|