-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncResponseCollection.php
62 lines (54 loc) · 1.75 KB
/
AsyncResponseCollection.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
<?php
namespace ScayTrase\Api\Rest;
use ScayTrase\Api\Rest\Exception\ProtocolException;
use ScayTrase\Api\Rpc\ResponseCollectionInterface;
use ScayTrase\Api\Rpc\RpcRequestInterface;
final class AsyncResponseCollection implements \IteratorAggregate, ResponseCollectionInterface
{
/** @var AsyncContainer[] */
private $containers;
/** @var ProtocolFactoryInterface */
private $factory;
/**
* AsyncResponseCollection constructor.
*
* @param AsyncContainer[] $containers
* @param ProtocolFactoryInterface $factory
*/
public function __construct(array $containers, ProtocolFactoryInterface $factory)
{
$this->containers = $this->reindex($containers);
$this->factory = $factory;
}
private function reindex(array $containers)
{
$indexed = [];
foreach ($containers as $container) {
$indexed[spl_object_hash($container->getRpcRequest())] = $container;
}
return $indexed;
}
/** {@inheritdoc} */
public function getIterator()
{
foreach ($this->containers as $container) {
yield $this->getResponse($this->$container->getRpcRequest());
}
}
/**
* {@inheritdoc}
* @throws ProtocolException
*/
public function getResponse(RpcRequestInterface $request)
{
$hash = spl_object_hash($request);
if (!array_key_exists($hash, $this->containers)) {
throw new \OutOfBoundsException('Response collection does not contain this request');
}
try {
return $this->factory->decode($this->containers[$hash]->getPromise()->wait());
} catch (\LogicException $e) {
throw new ProtocolException($e->getMessage());
}
}
}