1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace ekinhbayar\GitAmp\Client; |
4
|
|
|
|
5
|
|
|
use Amp\Promise; |
6
|
|
|
use Amp\Artax\Client; |
7
|
|
|
use Amp\Artax\ClientException; |
8
|
|
|
use Amp\Artax\Request; |
9
|
|
|
use Amp\Success; |
10
|
|
|
use ekinhbayar\GitAmp\Events\Factory; |
11
|
|
|
use ekinhbayar\GitAmp\Github\Credentials; |
12
|
|
|
use ekinhbayar\GitAmp\Response\Results; |
13
|
|
|
|
14
|
|
|
class GitAmp |
15
|
|
|
{ |
16
|
|
|
const API_ENDPOINT = 'https://api.github.com/events'; |
17
|
|
|
|
18
|
|
|
private $client; |
19
|
|
|
private $credentials; |
20
|
|
|
private $eventFactory; |
21
|
|
|
|
22
|
4 |
|
public function __construct(Client $client, Credentials $credentials, Factory $eventFactory) |
23
|
|
|
{ |
24
|
4 |
|
$this->client = $client; |
25
|
4 |
|
$this->credentials = $credentials; |
26
|
4 |
|
$this->eventFactory = $eventFactory; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @return Promise |
31
|
|
|
* @throws RequestFailedException |
32
|
|
|
*/ |
33
|
4 |
|
private function request(): Promise |
34
|
|
|
{ |
35
|
|
|
try { |
36
|
4 |
|
$request = (new Request) |
37
|
4 |
|
->setMethod('GET') |
38
|
4 |
|
->setUri(self::API_ENDPOINT) |
39
|
4 |
|
->setAllHeaders($this->getAuthHeader()); |
40
|
|
|
|
41
|
4 |
|
$promise = $this->client->request($request); |
42
|
|
|
|
43
|
|
|
$promise->when(function($error, $result) { |
44
|
3 |
|
if ($result->getStatus() !== 200) { |
45
|
1 |
|
throw new RequestFailedException( |
46
|
|
|
'A non-200 response status (' |
47
|
1 |
|
. $result->getStatus() . ' - ' |
48
|
1 |
|
. $result->getReason() . ') was encountered' |
49
|
|
|
); |
50
|
|
|
} |
51
|
3 |
|
}); |
52
|
|
|
|
53
|
2 |
|
return $promise; |
54
|
|
|
|
55
|
2 |
|
} catch (ClientException $e) { |
56
|
1 |
|
throw new RequestFailedException('Failed to send GET request to API endpoint', $e->getCode(), $e); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function listen(): Promise |
61
|
|
|
{ |
62
|
4 |
|
return \Amp\resolve(function() { |
63
|
4 |
|
$response = yield $this->request(); |
64
|
|
|
|
65
|
2 |
|
$results = new Results($this->eventFactory); |
66
|
|
|
|
67
|
2 |
|
$results->appendResponse($response); |
68
|
|
|
|
69
|
2 |
|
return new Success($results); |
70
|
4 |
|
}); |
71
|
|
|
} |
72
|
|
|
|
73
|
4 |
|
private function getAuthHeader(): array |
74
|
|
|
{ |
75
|
4 |
|
return ['Authorization' => sprintf('Basic %s', $this->credentials->getAuthenticationString())]; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
|