|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Http\Client\Common; |
|
4
|
|
|
|
|
5
|
|
|
use Http\Client\Exception\RequestException; |
|
6
|
|
|
use Http\Client\HttpAsyncClient; |
|
7
|
|
|
use Http\Client\HttpClient; |
|
8
|
|
|
use Http\Message\RequestMatcher; |
|
9
|
|
|
use Psr\Http\Message\RequestInterface; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Route a request to a specific client in the stack based using a RequestMatcher. |
|
13
|
|
|
* |
|
14
|
|
|
* @author Joel Wurtz <[email protected]> |
|
15
|
|
|
*/ |
|
16
|
|
|
class HttpClientRouter implements HttpClient, HttpAsyncClient |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* @var array |
|
20
|
|
|
*/ |
|
21
|
|
|
private $clients = []; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* {@inheritdoc} |
|
25
|
|
|
*/ |
|
26
|
2 |
|
public function sendAsyncRequest(RequestInterface $request) |
|
27
|
|
|
{ |
|
28
|
2 |
|
$client = $this->chooseHttpClient($request); |
|
29
|
|
|
|
|
30
|
1 |
|
return $client->sendAsyncRequest($request); |
|
|
|
|
|
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* {@inheritdoc} |
|
35
|
|
|
*/ |
|
36
|
2 |
|
public function sendRequest(RequestInterface $request) |
|
37
|
|
|
{ |
|
38
|
2 |
|
$client = $this->chooseHttpClient($request); |
|
39
|
|
|
|
|
40
|
1 |
|
return $client->sendRequest($request); |
|
|
|
|
|
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Add a client to the router. |
|
45
|
|
|
* |
|
46
|
|
|
* @param HttpClient|HttpAsyncClient $client |
|
47
|
|
|
* @param RequestMatcher $requestMatcher |
|
48
|
|
|
*/ |
|
49
|
4 |
|
public function addClient($client, RequestMatcher $requestMatcher) |
|
50
|
|
|
{ |
|
51
|
4 |
|
$this->clients[] = [ |
|
52
|
4 |
|
'matcher' => $requestMatcher, |
|
53
|
4 |
|
'client' => new FlexibleHttpClient($client) |
|
54
|
4 |
|
]; |
|
55
|
4 |
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* Choose an HTTP client given a specific request. |
|
59
|
|
|
* |
|
60
|
|
|
* @param RequestInterface $request |
|
61
|
|
|
* |
|
62
|
|
|
* @return HttpClient|HttpAsyncClient |
|
63
|
|
|
*/ |
|
64
|
4 |
|
protected function chooseHttpClient(RequestInterface $request) |
|
65
|
|
|
{ |
|
66
|
4 |
|
foreach ($this->clients as $client) { |
|
67
|
4 |
|
if ($client['matcher']->matches($request)) { |
|
68
|
2 |
|
return $client['client']; |
|
69
|
|
|
} |
|
70
|
2 |
|
} |
|
71
|
|
|
|
|
72
|
2 |
|
throw new RequestException('No client found for the specified request', $request); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|
It seems like the method you are trying to call exists only in some of the possible types.
Let’s take a look at an example:
Available Fixes
Add an additional type-check:
Only allow a single type to be passed if the variable comes from a parameter: