-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnectorPool.php
64 lines (53 loc) · 2.02 KB
/
ConnectorPool.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
declare(strict_types=1);
namespace Fansipan\Peak;
use Fansipan\Contracts\ConnectorInterface;
use Fansipan\Peak\Client\AsyncClientInterface;
use Fansipan\Peak\Exception\InvalidPoolRequestException;
use Fansipan\Peak\Exception\UnsupportedClientException;
use Fansipan\Request;
use Fansipan\Response;
if (! \interface_exists(ConnectorInterface::class)) {
// @codeCoverageIgnoreStart
throw new \LogicException('You cannot use the ConnectorPool as the "fansipan/fansipan" package is not installed.');
// @codeCoverageIgnoreEnd
}
/**
* @implements Pool<Request|callable(ConnectorInterface): Response, Response>
*/
final class ConnectorPool implements Pool
{
use PoolTrait;
private AsyncClientInterface $client;
public function __construct(private readonly ConnectorInterface $connector)
{
$client = $connector->client();
if (! $client instanceof AsyncClientInterface) {
// @codeCoverageIgnoreStart
throw new UnsupportedClientException(\sprintf(
'The client %s is not supported. Please swap the underlying client to supported one.',
\get_debug_type($client)
));
// @codeCoverageIgnoreEnd
}
$this->client = $client;
}
public function send(iterable $requests): array
{
$promises = static function (ConnectorInterface $connector, iterable $requests) {
/** @var array-key $key */
foreach ($requests as $key => $request) {
if ($request instanceof Request) {
yield $key => static fn (): Response => $connector->send($request);
} elseif (\is_callable($request)) {
yield $key => static fn (): Response => $request($connector);
} else {
throw new InvalidPoolRequestException(Request::class, Response::class);
}
}
};
return $this->createWorker($this->client)->run(
$promises($this->connector, $requests)
);
}
}