1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Http\Client\Common; |
6
|
|
|
|
7
|
|
|
use Http\Client\Common\Exception\HttpClientNoMatchException; |
8
|
|
|
use Http\Client\HttpAsyncClient; |
9
|
|
|
use Http\Message\RequestMatcher; |
10
|
|
|
use Psr\Http\Client\ClientInterface; |
11
|
|
|
use Psr\Http\Message\RequestInterface; |
12
|
|
|
use Psr\Http\Message\ResponseInterface; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* {@inheritdoc} |
16
|
|
|
* |
17
|
|
|
* @author Joel Wurtz <[email protected]> |
18
|
|
|
*/ |
19
|
|
|
final class HttpClientRouter implements HttpClientRouterInterface |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var array |
23
|
|
|
*/ |
24
|
|
|
private $clients = []; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
*/ |
29
|
2 |
|
public function sendRequest(RequestInterface $request): ResponseInterface |
30
|
|
|
{ |
31
|
2 |
|
return $this->chooseHttpClient($request)->sendRequest($request); |
|
|
|
|
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* {@inheritdoc} |
36
|
|
|
*/ |
37
|
2 |
|
public function sendAsyncRequest(RequestInterface $request) |
38
|
|
|
{ |
39
|
2 |
|
return $this->chooseHttpClient($request)->sendAsyncRequest($request); |
|
|
|
|
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Add a client to the router. |
44
|
|
|
* |
45
|
|
|
* @param ClientInterface|HttpAsyncClient $client |
46
|
|
|
*/ |
47
|
4 |
|
public function addClient($client, RequestMatcher $requestMatcher): void |
48
|
|
|
{ |
49
|
4 |
|
if (!$client instanceof ClientInterface && !$client instanceof HttpAsyncClient) { |
50
|
|
|
throw new \TypeError( |
51
|
|
|
sprintf('%s::addClient(): Argument #1 ($client) must be of type %s|%s, %s given', self::class, ClientInterface::class, HttpAsyncClient::class, get_debug_type($client)) |
|
|
|
|
52
|
|
|
); |
53
|
|
|
} |
54
|
|
|
|
55
|
4 |
|
$this->clients[] = [ |
56
|
4 |
|
'matcher' => $requestMatcher, |
57
|
4 |
|
'client' => new FlexibleHttpClient($client), |
58
|
|
|
]; |
59
|
4 |
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Choose an HTTP client given a specific request. |
63
|
|
|
* |
64
|
|
|
* @return ClientInterface|HttpAsyncClient |
65
|
|
|
*/ |
66
|
4 |
|
private function chooseHttpClient(RequestInterface $request) |
67
|
|
|
{ |
68
|
4 |
|
foreach ($this->clients as $client) { |
69
|
4 |
|
if ($client['matcher']->matches($request)) { |
70
|
2 |
|
return $client['client']; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
2 |
|
throw new HttpClientNoMatchException('No client found for the specified request', $request); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
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: