Completed
Push — master ( d94e2b...cf4bb1 )
by Pieter
27s
created

GitAmp   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 7
dl 0
loc 64
ccs 26
cts 26
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getAuthHeader() 0 4 1
A __construct() 0 6 1
B request() 0 26 3
A listen() 0 12 1
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