1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Http\Adapter\Guzzle6; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client as GuzzleClient; |
6
|
|
|
use GuzzleHttp\ClientInterface; |
7
|
|
|
use GuzzleHttp\HandlerStack; |
8
|
|
|
use GuzzleHttp\Middleware; |
9
|
|
|
use Http\Client\HttpAsyncClient; |
10
|
|
|
use Http\Client\HttpClient; |
11
|
|
|
use Psr\Http\Message\RequestInterface; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* HTTP Adapter for Guzzle 6. |
15
|
|
|
* |
16
|
|
|
* @author David de Boer <[email protected]> |
17
|
|
|
*/ |
18
|
|
|
class Client implements HttpClient, HttpAsyncClient |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var ClientInterface |
22
|
|
|
*/ |
23
|
|
|
private $client; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param ClientInterface|null $client |
27
|
|
|
*/ |
28
|
324 |
|
public function __construct(ClientInterface $client = null) |
29
|
|
|
{ |
30
|
324 |
|
if (!$client) { |
31
|
|
|
$client = static::buildClient(); |
|
|
|
|
32
|
|
|
} |
33
|
|
|
|
34
|
324 |
|
$this->client = $client; |
35
|
324 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Factory method to create the guzzle 6 adapter with custom configuration for guzzle. |
39
|
|
|
* |
40
|
|
|
* @param array $config Configuration to create guzzle with. |
41
|
|
|
* |
42
|
|
|
* @return Client |
43
|
|
|
*/ |
44
|
|
|
public static function createWithConfig(array $config) |
45
|
|
|
{ |
46
|
|
|
return new self(static::buildClient($config)); |
|
|
|
|
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* {@inheritdoc} |
51
|
|
|
*/ |
52
|
159 |
|
public function sendRequest(RequestInterface $request) |
53
|
|
|
{ |
54
|
159 |
|
$promise = $this->sendAsyncRequest($request); |
55
|
|
|
|
56
|
159 |
|
return $promise->wait(); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* {@inheritdoc} |
61
|
|
|
*/ |
62
|
324 |
|
public function sendAsyncRequest(RequestInterface $request) |
63
|
|
|
{ |
64
|
324 |
|
$promise = $this->client->sendAsync($request); |
65
|
|
|
|
66
|
324 |
|
return new Promise($promise, $request); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Build the guzzle client instance. |
71
|
|
|
* |
72
|
|
|
* @param array $config Additional configuration |
73
|
|
|
* |
74
|
|
|
* @return GuzzleClient |
75
|
|
|
*/ |
76
|
|
|
private static function buildClient(array $config) |
77
|
|
|
{ |
78
|
|
|
$handlerStack = new HandlerStack(\GuzzleHttp\choose_handler()); |
79
|
|
|
$handlerStack->push(Middleware::prepareBody(), 'prepare_body'); |
80
|
|
|
$config = array_merge(['handler' => $handlerStack], $config); |
81
|
|
|
|
82
|
|
|
return new GuzzleClient($config); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
Let’s assume you have a class which uses late-static binding:
}
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()
on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClass
to useself
instead: