PluginProbe
DecaLog / 4.4.0
DecaLog v4.4.0
3.0.2 3.1.0 3.10.0 3.2.0 3.3.0 3.4.0 3.4.1 3.5.0 3.5.1 3.6.0 3.6.1 3.6.2 3.6.3 3.7.0 3.7.1 3.8.0 3.9.0 3.9.1 4.0.0 4.1.0 4.2.0 4.3.0 4.3.1 4.4.0 4.5.0 All 75 releases
decalog / includes / libraries / http / client-common / HttpClientRouter.php

HttpClientRouter.php in DecaLog 4.4.0, at includes/libraries/http/client-common/HttpClientRouter.php

75 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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