Completed
Branch unit-tests (90fa68)
by Ekin
02:26
created

GitAmp   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 75%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 6
dl 0
loc 59
ccs 15
cts 20
cp 0.75
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A request() 0 14 2
A listen() 0 12 1
A getAuthHeader() 0 4 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\Events\GithubEventType;
12
use ekinhbayar\GitAmp\Github\Credentials;
13
use ekinhbayar\GitAmp\Response\Results;
14
15
/**
16
 * Class GitAmp
17
 * @package ekinhbayar\GitAmp\Client
18
 */
19
class GitAmp
20
{
21
    const API_ENDPOINT = 'https://api.github.com/events';
22
23
    /**
24
     * @var Client
25
     */
26
    private $client;
27
    private $credentials;
28
    private $eventFactory;
29
30
    /**
31
     * GitAmp constructor.
32
     * @param Client $client
33
     */
34 2
    public function __construct(Client $client, Credentials $credentials, Factory $eventFactory)
35
    {
36 2
        $this->client       = $client;
37 2
        $this->credentials  = $credentials;
38 2
        $this->eventFactory = $eventFactory;
39
    }
40
41
    /**
42
     * @return Promise
43
     * @throws RequestFailedException
44
     */
45 2
    public function request(): Promise
46
    {
47
        try {
48 2
            $request = (new Request)
49 2
                ->setMethod('GET')
50 2
                ->setUri(self::API_ENDPOINT)
51 2
                ->setAllHeaders($this->getAuthHeader());
52
53 2
            return $this->client->request($request);
54
55
        } catch (ClientException $e) {
56
            throw new RequestFailedException('Failed to send GET request to API endpoint', $e->getCode(), $e);
57
        }
58
    }
59
60
    public function listen(): Promise
61
    {
62 1
        return \Amp\resolve(function() {
63 1
            $response = yield $this->request();
64
65
            $results = new Results($this->eventFactory);
66
67
            $results->appendResponse($response);
68
69
            return new Success($results);
70 1
        });
71
    }
72
73 2
    private function getAuthHeader(): array
74
    {
75 2
        return ['Authorization' => sprintf('Basic %s', $this->credentials->getAuthenticationString())];
76
    }
77
}
78