Completed
Pull Request — master (#4)
by
unknown
05:50
created

Client::sendRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
crap 3
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\Api\Request\Stream\Request as StreamRequest;
24
use PeeHaa\AsyncTwitter\Credentials\AccessToken;
25
use PeeHaa\AsyncTwitter\Credentials\Application;
26
use PeeHaa\AsyncTwitter\Http\Client as HttpClient;
27
use PeeHaa\AsyncTwitter\Oauth\Header;
28
use PeeHaa\AsyncTwitter\Oauth\Parameters;
29
use PeeHaa\AsyncTwitter\Oauth\Signature\BaseString;
30
use PeeHaa\AsyncTwitter\Oauth\Signature\Key;
31
use PeeHaa\AsyncTwitter\Oauth\Signature\Signature;
32
use PeeHaa\AsyncTwitter\Request\Body;
33
use PeeHaa\AsyncTwitter\Request\Parameter;
34
use PeeHaa\AsyncTwitter\Request\Url;
35
use function Amp\resolve;
36
use function ExceptionalJSON\decode as json_try_decode;
37
38
class Client
39
{
40
    private $httpClient;
41
42
    private $applicationCredentials;
43
44
    private $accessToken;
45
46 19
    public function __construct(HttpClient $httpClient, Application $applicationCredentials, AccessToken $accessToken)
47
    {
48 19
        $this->httpClient             = $httpClient;
49 19
        $this->applicationCredentials = $applicationCredentials;
50 19
        $this->accessToken            = $accessToken;
51 19
    }
52
53 18
    public function request(Request $request): Promise
54
    {
55 18
        return $request instanceof StreamRequest
56
            ? $this->openStream($request)
57 18
            : $this->handleResponse($this->sendRequest($request));
58
    }
59
60 18
    private function sendRequest(Request $request)
61
    {
62 18
        switch ($request->getMethod()) {
63 18
            case 'POST':
64 16
                return $this->post($request);
65
66 2
            case 'GET':
67 1
                return $this->get($request);
68
69
            default:
70 1
                throw new InvalidMethod();
71
        }
72
    }
73
74
    private function openStream(StreamRequest $request): Promise
75
    {
76
        $watcher = new StreamReader;
77
78
        $this->sendRequest($request)->watch([$watcher, 'onProgress']);
79
80
        return $watcher->awaitStreamOpen();
81
    }
82
83 16
    private function getErrorStringFromResponseBody(array $body): array
84
    {
85 16
        if (!isset($body['errors'])) {
86 2
            return ['Unknown error', -1, []];
87
        }
88
89 14
        $firstError = array_shift($body['errors']);
90
91 14
        $message = $firstError['message'] ?? 'Unknown error';
92 14
        $code    = $firstError['code'] ?? -1;
93 14
        $extra   = [];
94
95 14
        foreach ($body['errors'] as $error) {
96
            $extra[($error['code'] ?? -1)] = ($error['message'] ?? 'Unknown error');
97
        }
98
99 14
        return [$message, $code, $extra];
100
    }
101
102
    // https://dev.twitter.com/overview/api/response-codes
103 16
    private function throwFromErrorResponse(HttpResponse $response, array $body)
104
    {
105 16
        list($message, $code, $extra) = $this->getErrorStringFromResponseBody($body);
106
107
        $exceptions = [
108 16
            400 => BadRequest::class,
109
            401 => Unauthorized::class,
110
            403 => Forbidden::class,
111
            404 => NotFound::class,
112
            406 => NotAcceptable::class,
113
            410 => Gone::class,
114
            420 => RateLimitTriggered::class,
115
            422 => UnprocessableEntity::class,
116
            429 => RateLimitTriggered::class,
117
            500 => ServerError::class,
118
            502 => BadGateway::class,
119
            503 => ServiceUnavailable::class,
120
            504 => GatewayTimeout::class,
121
        ];
122
123 16
        if (!array_key_exists($response->getStatus(), $exceptions)) {
124 3
            return;
125
        }
126
127 13
        throw new $exceptions[$response->getStatus()]($message, $code, null, $extra);
128
    }
129
130
    private function handleResponse(Promise $responsePromise): Promise
131
    {
132 17
        return resolve(function() use($responsePromise) {
133
            /** @var HttpResponse $response */
134 17
            $response = yield $responsePromise;
135
136
            try {
137 17
                $decoded = json_try_decode($response->getBody(), true);
138 1
            } catch (JSONDecodeErrorException $e) {
139 1
                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...
140
            }
141
142 16
            $this->throwFromErrorResponse($response, $decoded);
143
144 3
            return $decoded;
145 17
        });
146
    }
147
148 16 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...
149
    {
150 16
        $header = $this->getHeader('POST', $request->getEndpoint(), ...$request->getParameters());
151
152 16
        $flags = 0;
153 16
        if ($request instanceof StreamRequest) {
154
            $flags |= HttpClient::OP_STREAM;
155
        }
156
157 16
        return $this->httpClient->post($request->getEndpoint(), $header, new Body(...$request->getParameters()), $flags);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
158
    }
159
160 1 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...
161
    {
162 1
        $header = $this->getHeader('GET', $request->getEndpoint(), ...$request->getParameters());
163
164 1
        $flags = 0;
165 1
        if ($request instanceof StreamRequest) {
166
            $flags |= HttpClient::OP_STREAM;
167
        }
168
169 1
        return $this->httpClient->get($request->getEndpoint(), $header, $request->getParameters(), $flags);
170
    }
171
172 17
    private function getHeader(string $method, Url $url, Parameter ...$parameters): Header
173
    {
174 17
        $oauthParameters     = new Parameters($this->applicationCredentials, $this->accessToken, $url, ...$parameters);
175 17
        $baseSignatureString = new BaseString($method, $url, $oauthParameters);
176 17
        $signingKey          = new Key($this->applicationCredentials, $this->accessToken);
177 17
        $signature           = new Signature($baseSignatureString, $signingKey);
178
179 17
        return new Header($oauthParameters, $signature);
180
    }
181
}
182