Completed
Push — master ( 382fef...8bf8f9 )
by Pieter
03:12
created

Client   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 164
Duplicated Lines 13.41 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 84.51%

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 13
dl 22
loc 164
ccs 60
cts 71
cp 0.8451
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B throwFromErrorResponse() 0 26 2
A request() 0 6 2
A sendRequest() 0 17 3
A openStream() 0 8 1
A getErrorStringFromResponseBody() 0 18 3
B handleResponse() 0 22 4
A post() 11 11 2
A get() 11 11 2
A getHeader() 0 20 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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