Passed
Branch v2_rewrite (3ed97e)
by Ekin
09:32
created

GitAmp::checkForRequestErrors()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.054

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 9
cts 11
cp 0.8182
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 11
nc 3
nop 2
crap 3.054

2 Methods

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