1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ekinhbayar\GitAmp\Response; |
4
|
|
|
|
5
|
|
|
use Amp\Http\Client\Response; |
6
|
|
|
use Amp\Promise; |
7
|
|
|
use ekinhbayar\GitAmp\Event\Factory as EventFactory; |
8
|
|
|
use ekinhbayar\GitAmp\Exception\DecodingFailed; |
9
|
|
|
use ekinhbayar\GitAmp\Exception\UnknownEvent; |
10
|
|
|
use ExceptionalJSON\DecodeErrorException; |
11
|
|
|
use Psr\Log\LoggerInterface; |
12
|
|
|
use function Amp\call; |
13
|
|
|
|
14
|
|
|
class Results |
15
|
|
|
{ |
16
|
|
|
private EventFactory $eventFactory; |
17
|
|
|
|
18
|
|
|
private LoggerInterface $logger; |
19
|
|
|
|
20
|
|
|
private array $events = []; |
21
|
|
|
|
22
|
9 |
|
public function __construct(EventFactory $eventFactory, LoggerInterface $logger) |
23
|
|
|
{ |
24
|
9 |
|
$this->eventFactory = $eventFactory; |
25
|
9 |
|
$this->logger = $logger; |
26
|
9 |
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @return Promise<null> |
30
|
|
|
*/ |
31
|
6 |
|
public function appendResponse(string $eventNamespace, Response $response): Promise |
32
|
|
|
{ |
33
|
6 |
|
return call(function () use ($eventNamespace, $response) { |
34
|
|
|
try { |
35
|
6 |
|
$bufferedResponse = yield $response->getBody()->buffer(); |
36
|
|
|
|
37
|
6 |
|
$events = \json_try_decode($bufferedResponse, true); |
38
|
1 |
|
} catch (DecodeErrorException $e) { |
39
|
1 |
|
$this->logger->emergency('Failed to decode response body as JSON', ['exception' => $e]); |
40
|
|
|
|
41
|
1 |
|
throw new DecodingFailed('Failed to decode response body as JSON', $e->getCode(), $e); |
42
|
|
|
} |
43
|
|
|
|
44
|
5 |
|
foreach ($events as $event) { |
45
|
5 |
|
$this->appendEvent($eventNamespace, $event); |
46
|
|
|
} |
47
|
6 |
|
}); |
48
|
|
|
} |
49
|
|
|
|
50
|
5 |
|
private function appendEvent(string $eventNamespace, array $event): void |
51
|
|
|
{ |
52
|
|
|
try { |
53
|
5 |
|
$this->events[] = $this->eventFactory->build($eventNamespace, $event); |
54
|
2 |
|
} catch (UnknownEvent $e) { |
55
|
|
|
//$this->logger->debug('Unknown event encountered', ['exception' => $e]); |
56
|
|
|
} |
57
|
5 |
|
} |
58
|
|
|
|
59
|
2 |
|
public function hasEvents(): bool |
60
|
|
|
{ |
61
|
2 |
|
return (bool) \count($this->events); |
62
|
|
|
} |
63
|
|
|
|
64
|
2 |
|
public function jsonEncode(): string |
65
|
|
|
{ |
66
|
2 |
|
$events = []; |
67
|
|
|
|
68
|
2 |
|
foreach ($this->events as $event) { |
69
|
1 |
|
$events[] = $event->getAsArray(); |
70
|
|
|
} |
71
|
|
|
|
72
|
2 |
|
return \json_encode($events); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|