Completed
Push — master ( 5e3ebb...42c5bb )
by Pieter
02:29
created

Client::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php declare(strict_types=1);
2
3
namespace PeeHaa\AsyncTwitter\Api\Client;
4
5
use Amp\Artax\Response as HttpResponse;
6
use Amp\Promise;
7
use ExceptionalJSON\DecodeErrorException as JSONDecodeErrorException;
8
use PeeHaa\AsyncTwitter\Api\Client\Exception\BadGateway;
9
use PeeHaa\AsyncTwitter\Api\Client\Exception\BadRequest;
10
use PeeHaa\AsyncTwitter\Api\Client\Exception\Forbidden;
11
use PeeHaa\AsyncTwitter\Api\Client\Exception\GatewayTimeout;
12
use PeeHaa\AsyncTwitter\Api\Client\Exception\Gone;
13
use PeeHaa\AsyncTwitter\Api\Client\Exception\InvalidMethod;
14
use PeeHaa\AsyncTwitter\Api\Client\Exception\NotAcceptable;
15
use PeeHaa\AsyncTwitter\Api\Client\Exception\NotFound;
16
use PeeHaa\AsyncTwitter\Api\Client\Exception\RateLimitTriggered;
17
use PeeHaa\AsyncTwitter\Api\Client\Exception\RequestFailed;
18
use PeeHaa\AsyncTwitter\Api\Client\Exception\ServerError;
19
use PeeHaa\AsyncTwitter\Api\Client\Exception\ServiceUnavailable;
20
use PeeHaa\AsyncTwitter\Api\Client\Exception\Unauthorized;
21
use PeeHaa\AsyncTwitter\Api\Client\Exception\UnprocessableEntity;
22
use PeeHaa\AsyncTwitter\Api\Request\Request;
23
use PeeHaa\AsyncTwitter\Credentials\AccessToken;
24
use PeeHaa\AsyncTwitter\Credentials\Application;
25
use PeeHaa\AsyncTwitter\Http\Client as HttpClient;
26
use PeeHaa\AsyncTwitter\Oauth\Header;
27
use PeeHaa\AsyncTwitter\Oauth\Parameters;
28
use PeeHaa\AsyncTwitter\Oauth\Signature\BaseString;
29
use PeeHaa\AsyncTwitter\Oauth\Signature\Key;
30
use PeeHaa\AsyncTwitter\Oauth\Signature\Signature;
31
use PeeHaa\AsyncTwitter\Request\Body;
32
use PeeHaa\AsyncTwitter\Request\Parameter;
33
use PeeHaa\AsyncTwitter\Request\Url;
34
use function Amp\resolve;
35
use function ExceptionalJSON\decode as json_try_decode;
36
37
class Client
38
{
39
    private $httpClient;
40
41
    private $applicationCredentials;
42
43
    private $accessToken;
44
45 1
    public function __construct(HttpClient $httpClient, Application $applicationCredentials, AccessToken $accessToken)
46
    {
47 1
        $this->httpClient             = $httpClient;
48 1
        $this->applicationCredentials = $applicationCredentials;
49 1
        $this->accessToken            = $accessToken;
50 1
    }
51
52
    public function request(Request $request): Promise
53
    {
54
        switch ($request->getMethod()) {
55
            case 'POST':
56
                return $this->post($request);
57
58
            case 'GET':
59
                return $this->get($request);
60
61
            default:
62
                throw new InvalidMethod();
63
        }
64
    }
65
66
    private function getErrorStringFromResponseBody(array $body): array
67
    {
68
        if (!isset($body['errors'])) {
69
            return ['Unknown error', -1, []];
70
        }
71
72
        $firstError = array_shift($body['errors']);
73
74
        $message = $firstError['message'] ?? 'Unknown error';
75
        $code    = $firstError['code'] ?? -1;
76
        $extra   = [];
77
78
        foreach ($body['errors'] as $error) {
79
            $extra[($error['code'] ?? -1)] = ($error['message'] ?? 'Unknown error');
80
        }
81
82
        return [$message, $code, $extra];
83
    }
84
85
    // https://dev.twitter.com/overview/api/response-codes
86
    private function throwFromErrorResponse(HttpResponse $response, array $body)
87
    {
88
        list($message, $code, $extra) = $this->getErrorStringFromResponseBody($body);
89
90
        $exceptions = [
91
            400 => BadRequest::class,
92
            401 => Unauthorized::class,
93
            403 => Forbidden::class,
94
            404 => NotFound::class,
95
            406 => NotAcceptable::class,
96
            410 => Gone::class,
97
            420 => RateLimitTriggered::class,
98
            422 => UnprocessableEntity::class,
99
            429 => RateLimitTriggered::class,
100
            500 => ServerError::class,
101
            502 => BadGateway::class,
102
            503 => ServiceUnavailable::class,
103
            504 => GatewayTimeout::class,
104
        ];
105
106
        if (!array_key_exists($response->getStatus(), $exceptions)) {
107
            return;
108
        }
109
110
        throw new $exceptions[$response->getStatus()]($message, $code, null, $extra);
111
    }
112
113
    private function handleResponse(Promise $responsePromise): Promise
114
    {
115
        return resolve(function() use($responsePromise) {
116
            /** @var HttpResponse $response */
117
            $response = yield $responsePromise;
118
119
            try {
120
                $decoded = json_try_decode($response->getBody(), true);
121
            } catch (JSONDecodeErrorException $e) {
122
                throw new RequestFailed('Failed to decode response body as JSON', $e->getCode(), $e);
0 ignored issues
show
Documentation introduced by
$e is of type object<ExceptionalJSON\DecodeErrorException>, but the function expects a null|object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
123
            }
124
125
            $this->throwFromErrorResponse($response, $decoded);
126
127
            return $decoded;
128
        });
129
    }
130
131 View Code Duplication
    private function post(Request $request): Promise
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
    {
133
        $header   = $this->getHeader('POST', $request->getEndpoint(), ...$request->getParameters());
134
        $response = $this->httpClient->post($request->getEndpoint(), $header, new Body(...$request->getParameters()));
135
136
        return $this->handleResponse($response);
137
    }
138
139 View Code Duplication
    private function get(Request $request): Promise
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
140
    {
141
        $header   = $this->getHeader('GET', $request->getEndpoint(), ...$request->getParameters());
142
        $response = $this->httpClient->get($request->getEndpoint(), $header, ...$request->getParameters());
143
144
        return $this->handleResponse($response);
145
    }
146
147
    private function getHeader(string $method, Url $url, Parameter ...$parameters): Header
148
    {
149
        $oauthParameters     = new Parameters($this->applicationCredentials, $this->accessToken, $url, ...$parameters);
150
        $baseSignatureString = new BaseString($method, $url, $oauthParameters);
151
        $signingKey          = new Key($this->applicationCredentials, $this->accessToken);
152
        $signature           = new Signature($baseSignatureString, $signingKey);
153
154
        return new Header($oauthParameters, $signature);
155
    }
156
}
157