Passed
Branch unit-tests (1207b4)
by Ekin
02:32
created

GitAmp::request()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 14
cts 14
cp 1
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 16
nc 4
nop 0
crap 3
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