Client::sendRequest()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 6.087

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 3
cts 10
cp 0.3
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 3
nop 1
crap 6.087
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\FileParameter;
34
use PeeHaa\AsyncTwitter\Request\Parameter;
35
use PeeHaa\AsyncTwitter\Request\Url;
36
use function Amp\resolve;
37
use function ExceptionalJSON\decode as json_try_decode;
38
39
class Client
40
{
41
    private $httpClient;
42
43
    private $applicationCredentials;
44
45
    private $accessToken;
46
47 15
    public function __construct(HttpClient $httpClient, Application $applicationCredentials, AccessToken $accessToken)
48
    {
49 15
        $this->httpClient             = $httpClient;
50 15
        $this->applicationCredentials = $applicationCredentials;
51 15
        $this->accessToken            = $accessToken;
52
    }
53
54 1
    public function request(Request $request): Promise
55
    {
56 1
        return $request instanceof StreamRequest
57
            ? $this->openStream($request)
58 1
            : $this->sendRequest($request);
59
    }
60
61 1
    private function sendRequest(Request $request)
62
    {
63 1
        switch ($request->getMethod()) {
64
            case 'POST':
65
                $responsePromise = $this->post($request);
66
                break;
67
68
            case 'GET':
69
                $responsePromise = $this->get($request);
70
                break;
71
72
            default:
73 1
                throw new InvalidMethod();
74
        }
75
76
        return resolve($this->handleResponse($request, $responsePromise));
77
    }
78
79
    private function openStream(StreamRequest $request): Promise
80
    {
81
        $watcher = new StreamReader;
82
83
        $this->sendRequest($request)->watch([$watcher, 'onProgress']);
84
85
        return $watcher->awaitStreamOpen();
86
    }
87
88
    private function getErrorStringFromResponseBody(array $body): array
89
    {
90
        if (!isset($body['errors'])) {
91
            return ['Unknown error', -1, []];
92
        }
93
94
        $firstError = array_shift($body['errors']);
95
96
        $message = $firstError['message'] ?? 'Unknown error';
97
        $code    = $firstError['code'] ?? -1;
98
        $extra   = [];
99
100
        foreach ($body['errors'] as $error) {
101
            $extra[($error['code'] ?? -1)] = ($error['message'] ?? 'Unknown error');
102
        }
103
104
        return [$message, $code, $extra];
105
    }
106
107
    // https://dev.twitter.com/overview/api/response-codes
108
    private function throwFromErrorResponse(HttpResponse $response, array $body)
109
    {
110
        list($message, $code, $extra) = $this->getErrorStringFromResponseBody($body);
111
112
        $exceptions = [
113
            400 => BadRequest::class,
114
            401 => Unauthorized::class,
115
            403 => Forbidden::class,
116
            404 => NotFound::class,
117
            406 => NotAcceptable::class,
118
            410 => Gone::class,
119
            420 => RateLimitTriggered::class,
120
            422 => UnprocessableEntity::class,
121
            429 => RateLimitTriggered::class,
122
            500 => ServerError::class,
123
            502 => BadGateway::class,
124
            503 => ServiceUnavailable::class,
125
            504 => GatewayTimeout::class,
126
        ];
127
128
        if (!array_key_exists($response->getStatus(), $exceptions)) {
129
            return;
130
        }
131
132
        throw new $exceptions[$response->getStatus()]($message, $code, null, $extra);
133
    }
134
135
    private function handleResponse(Request $request, Promise $responsePromise)
136
    {
137
        /** @var HttpResponse $response */
138
        $response = yield $responsePromise;;
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
139
140
        // @todo for v2 we need to make this less stupid by properly handling responses
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
141
        //       instead of this band-aid solution. and just this is bad and I feel bad.
142
        //       *dealwithit.gif*
143
        if ($response->getStatus() === 200 && $response->getBody() === null) {
144
            return null;
145
        }
146
147
        try {
148
            $decoded = json_try_decode($response->getBody(), true);
0 ignored issues
show
Documentation introduced by
$response->getBody() is of type object<Amp\ByteStream\Message>, but the function expects a string.

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...
149
        } catch (JSONDecodeErrorException $e) {
150
            throw new RequestFailed('Failed to decode response body as JSON', $e->getCode(), $e);
151
        }
152
153
        $this->throwFromErrorResponse($response, $decoded);
154
155
        return $request->handleResponse($decoded);
156
    }
157
158 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...
159
    {
160
        $header = $this->getHeader('POST', $request->getEndpoint(), ...$request->getParameters());
161
162
        $flags = 0;
163
        if ($request instanceof StreamRequest) {
164
            $flags |= HttpClient::OP_STREAM;
165
        }
166
167
        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...
168
    }
169
170 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...
171
    {
172
        $header = $this->getHeader('GET', $request->getEndpoint(), ...$request->getParameters());
173
174
        $flags = 0;
175
        if ($request instanceof StreamRequest) {
176
            $flags |= HttpClient::OP_STREAM;
177
        }
178
179
        return $this->httpClient->get($request->getEndpoint(), $header, $request->getParameters(), $flags);
180
    }
181
182
    private function getHeader(string $method, Url $url, Parameter ...$parameters): Header
183
    {
184
        $params = [];
185
186
        foreach ($parameters as $parameter) {
187
            if ($parameter instanceof FileParameter) {
188
                $params = [];
189
                break;
190
            }
191
192
            $params[] = $parameter;
193
        }
194
195
        $oauthParameters     = new Parameters($this->applicationCredentials, $this->accessToken, $url, ...$params);
196
        $baseSignatureString = new BaseString($method, $url, $oauthParameters);
197
        $signingKey          = new Key($this->applicationCredentials, $this->accessToken);
198
        $signature           = new Signature($baseSignatureString, $signingKey);
199
200
        return new Header($oauthParameters, $signature);
201
    }
202
}
203