| 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 <joel.wurtz@gmail.com> |
| 18 |
*/ |
| 19 |
final class HttpClientRouter implements HttpClientRouterInterface |
| 20 |
{ |
| 21 |
/** |
| 22 |
* @var (array{matcher: RequestMatcher, client: FlexibleHttpClient})[] |
| 23 |
*/ |
| 24 |
private $clients = []; |
| 25 |
|
| 26 |
/** |
| 27 |
* {@inheritdoc} |
| 28 |
*/ |
| 29 |
public function sendRequest(RequestInterface $request): ResponseInterface |
| 30 |
{ |
| 31 |
return $this->chooseHttpClient($request)->sendRequest($request); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* {@inheritdoc} |
| 36 |
*/ |
| 37 |
public function sendAsyncRequest(RequestInterface $request) |
| 38 |
{ |
| 39 |
return $this->chooseHttpClient($request)->sendAsyncRequest($request); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Add a client to the router. |
| 44 |
* |
| 45 |
* @param ClientInterface|HttpAsyncClient $client |
| 46 |
*/ |
| 47 |
public function addClient($client, RequestMatcher $requestMatcher): void |
| 48 |
{ |
| 49 |
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 |
$this->clients[] = [ |
| 56 |
'matcher' => $requestMatcher, |
| 57 |
'client' => new FlexibleHttpClient($client), |
| 58 |
]; |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Choose an HTTP client given a specific request. |
| 63 |
*/ |
| 64 |
private function chooseHttpClient(RequestInterface $request): FlexibleHttpClient |
| 65 |
{ |
| 66 |
foreach ($this->clients as $client) { |
| 67 |
if ($client['matcher']->matches($request)) { |
| 68 |
return $client['client']; |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
throw new HttpClientNoMatchException('No client found for the specified request', $request); |
| 73 |
} |
| 74 |
} |
| 75 |
|