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 Psr\Http\Message\RequestInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* |
12
|
|
|
*/ |
13
|
|
|
class HttpClientRouter implements HttpClient, HttpAsyncClient |
14
|
|
|
{ |
15
|
|
|
private $clients = []; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* {@inheritdoc} |
19
|
|
|
*/ |
20
|
2 |
|
public function sendAsyncRequest(RequestInterface $request) |
21
|
|
|
{ |
22
|
2 |
|
$client = $this->chooseHttpClient($request); |
23
|
|
|
|
24
|
1 |
|
return $client->sendAsyncRequest($request); |
|
|
|
|
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* {@inheritdoc} |
29
|
|
|
*/ |
30
|
2 |
|
public function sendRequest(RequestInterface $request) |
31
|
|
|
{ |
32
|
2 |
|
$client = $this->chooseHttpClient($request); |
33
|
|
|
|
34
|
1 |
|
return $client->sendRequest($request); |
|
|
|
|
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Add a client to the router |
39
|
|
|
* |
40
|
|
|
* @param HttpClient|HttpAsyncClient $client |
41
|
|
|
* @param RequestMatcher $requestMatcher |
42
|
|
|
*/ |
43
|
4 |
|
public function addClient($client, RequestMatcher $requestMatcher) |
44
|
|
|
{ |
45
|
4 |
|
$this->clients[] = [ |
46
|
4 |
|
'matcher' => $requestMatcher, |
47
|
4 |
|
'client' => new HttpClientFlexible($client) |
48
|
4 |
|
]; |
49
|
4 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Choose a http client given a specific request |
53
|
|
|
* |
54
|
|
|
* @param RequestInterface $request |
55
|
|
|
* |
56
|
|
|
* @return HttpClient|HttpAsyncClient |
57
|
|
|
*/ |
58
|
4 |
|
protected function chooseHttpClient(RequestInterface $request) |
59
|
|
|
{ |
60
|
4 |
|
foreach ($this->clients as $client) { |
61
|
4 |
|
if ($client['matcher']->matches($request)) { |
62
|
2 |
|
return $client['client']; |
63
|
|
|
} |
64
|
2 |
|
} |
65
|
|
|
|
66
|
2 |
|
throw new RequestException('No client found for the specified request', $request); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
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: