Passed
Push — master ( 0340e7...1414a0 )
by Pieter
36s
created

Client::openStream()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 2
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 19
    public function __construct(HttpClient $httpClient, Application $applicationCredentials, AccessToken $accessToken)
48
    {
49 19
        $this->httpClient             = $httpClient;
50 19
        $this->applicationCredentials = $applicationCredentials;
51 19
        $this->accessToken            = $accessToken;
52
    }
53
54 18
    public function request(Request $request): Promise
55
    {
56 18
        return $request instanceof StreamRequest
57
            ? $this->openStream($request)
58 18
            : $this->sendRequest($request);
59
    }
60
61 18
    private function sendRequest(Request $request)
62
    {
63 18
        switch ($request->getMethod()) {
64 18
            case 'POST':
65 16
                $responsePromise = $this->post($request);
66 16
                break;
67
68 2
            case 'GET':
69 1
                $responsePromise = $this->get($request);
70 1
                break;
71
72
            default:
73 1
                throw new InvalidMethod();
74
        }
75
76 17
        return resolve($this->handleResponse($request, $responsePromise));
0 ignored issues
show
Documentation introduced by
$this->handleResponse($request, $responsePromise) is of type object<Generator>, but the function expects a callable.

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...
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 16
    private function getErrorStringFromResponseBody(array $body): array
89
    {
90 16
        if (!isset($body['errors'])) {
91 2
            return ['Unknown error', -1, []];
92
        }
93
94 14
        $firstError = array_shift($body['errors']);
95
96 14
        $message = $firstError['message'] ?? 'Unknown error';
97 14
        $code    = $firstError['code'] ?? -1;
98 14
        $extra   = [];
99
100 14
        foreach ($body['errors'] as $error) {
101
            $extra[($error['code'] ?? -1)] = ($error['message'] ?? 'Unknown error');
102
        }
103
104 14
        return [$message, $code, $extra];
105
    }
106
107
    // https://dev.twitter.com/overview/api/response-codes
108 16
    private function throwFromErrorResponse(HttpResponse $response, array $body)
109
    {
110 16
        list($message, $code, $extra) = $this->getErrorStringFromResponseBody($body);
111
112
        $exceptions = [
113 16
            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 16
        if (!array_key_exists($response->getStatus(), $exceptions)) {
129 3
            return;
130
        }
131
132 13
        throw new $exceptions[$response->getStatus()]($message, $code, null, $extra);
133
    }
134
135 17
    private function handleResponse(Request $request, Promise $responsePromise)
136
    {
137
        /** @var HttpResponse $response */
138 17
        $response = yield $responsePromise;
139
140
        try {
141 17
            $decoded = json_try_decode($response->getBody(), true);
142 1
        } catch (JSONDecodeErrorException $e) {
143 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...
144
        }
145
146 16
        $this->throwFromErrorResponse($response, $decoded);
147
148 3
        return $request->handleResponse($decoded);
149
    }
150
151 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...
152
    {
153 16
        $header = $this->getHeader('POST', $request->getEndpoint(), ...$request->getParameters());
154
155 16
        $flags = 0;
156 16
        if ($request instanceof StreamRequest) {
157
            $flags |= HttpClient::OP_STREAM;
158
        }
159
160 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...
161
    }
162
163 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...
164
    {
165 1
        $header = $this->getHeader('GET', $request->getEndpoint(), ...$request->getParameters());
166
167 1
        $flags = 0;
168 1
        if ($request instanceof StreamRequest) {
169
            $flags |= HttpClient::OP_STREAM;
170
        }
171
172 1
        return $this->httpClient->get($request->getEndpoint(), $header, $request->getParameters(), $flags);
173
    }
174
175 17
    private function getHeader(string $method, Url $url, Parameter ...$parameters): Header
176
    {
177 17
        $params = [];
178
179 17
        foreach ($parameters as $parameter) {
180 17
            if ($parameter instanceof FileParameter) {
181
                $params = [];
182
                break;
183
            }
184
185 17
            $params[] = $parameter;
186
        }
187
188 17
        $oauthParameters     = new Parameters($this->applicationCredentials, $this->accessToken, $url, ...$params);
189 17
        $baseSignatureString = new BaseString($method, $url, $oauthParameters);
190 17
        $signingKey          = new Key($this->applicationCredentials, $this->accessToken);
191 17
        $signature           = new Signature($baseSignatureString, $signingKey);
192
193 17
        return new Header($oauthParameters, $signature);
194
    }
195
}
196