Passed
Branch unit-tests (5d0ce8)
by Ekin
02:24
created

GitAmp::request()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 6
cts 8
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 3
nop 0
crap 2.0625
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