Completed
Push — master ( ec2444...4993cd )
by Pieter
03:27
created

Client   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 120
Duplicated Lines 11.67 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 11
dl 14
loc 120
ccs 0
cts 87
cp 0
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A request() 0 13 3
A getErrorStringFromResponseBody() 0 18 3
B throwFromErrorResponse() 0 26 2
A handleResponse() 0 17 2
A post() 7 7 1
A get() 7 7 1
A getHeader() 0 9 1

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;
4
5
use Amp\Artax\Response as HttpResponse;
6
use Amp\Promise;
7
use ExceptionalJSON\DecodeErrorException as JSONDecodeErrorException;
8
use PeeHaa\AsyncTwitter\Credentials\AccessToken;
9
use PeeHaa\AsyncTwitter\Credentials\Application;
10
use PeeHaa\AsyncTwitter\Http\Artax;
11
use PeeHaa\AsyncTwitter\Oauth\Header;
12
use PeeHaa\AsyncTwitter\Oauth\Parameters;
13
use PeeHaa\AsyncTwitter\Oauth\Signature\BaseString;
14
use PeeHaa\AsyncTwitter\Oauth\Signature\Key;
15
use PeeHaa\AsyncTwitter\Oauth\Signature\Signature;
16
use PeeHaa\AsyncTwitter\Request\Body;
17
use PeeHaa\AsyncTwitter\Request\Parameter;
18
use PeeHaa\AsyncTwitter\Request\Url;
19
use function Amp\resolve;
20
use function ExceptionalJSON\decode as json_try_decode;
21
22
class Client
23
{
24
    private $httpClient;
25
26
    private $applicationCredentials;
27
28
    private $accessToken;
29
30
    public function __construct(Artax $httpClient, Application $applicationCredentials, AccessToken $accessToken)
31
    {
32
        $this->httpClient             = $httpClient;
33
        $this->applicationCredentials = $applicationCredentials;
34
        $this->accessToken            = $accessToken;
35
    }
36
37
    public function request(Request $request): Promise
38
    {
39
        switch ($request->getMethod()) {
40
            case 'POST':
41
                return $this->post($request);
42
43
            case 'GET':
44
                return $this->get($request);
45
46
            default:
47
                throw new InvalidMethodException();
48
        }
49
    }
50
51
    private function getErrorStringFromResponseBody(array $body): array
52
    {
53
        if (!isset($body['errors'])) {
54
            return ['Unknown error', -1, []];
55
        }
56
57
        $firstError = array_shift($body['errors']);
58
59
        $message = $firstError['message'] ?? 'Unknown error';
60
        $code    = $firstError['code'] ?? -1;
61
        $extra   = [];
62
63
        foreach ($body['errors'] as $error) {
64
            $extra[($error['code'] ?? -1)] = ($error['message'] ?? 'Unknown error');
65
        }
66
67
        return [$message, $code, $extra];
68
    }
69
70
    // https://dev.twitter.com/overview/api/response-codes
71
    private function throwFromErrorResponse(HttpResponse $response, array $body)
72
    {
73
        list($message, $code, $extra) = $this->getErrorStringFromResponseBody($body);
74
75
        $exceptions = [
76
            400 => BadRequestException::class,
77
            401 => UnauthorizedException::class,
78
            403 => ForbiddenException::class,
79
            404 => NotFoundException::class,
80
            406 => NotAcceptableException::class,
81
            410 => GoneException::class,
82
            420 => RateLimitTriggeredException::class,
83
            422 => UnprocessableEntityException::class,
84
            429 => RateLimitTriggeredException::class,
85
            500 => ServerErrorException::class,
86
            502 => BadGatewayException::class,
87
            503 => ServiceUnavailableException::class,
88
            504 => GatewayTimeoutException::class,
89
        ];
90
91
        if (!array_key_exists($response->getStatus(), $exceptions)) {
92
            return;
93
        }
94
95
        throw new $exceptions[$response->getStatus()]($message, $code, null, $extra);
96
    }
97
98
    private function handleResponse(Promise $responsePromise): Promise
99
    {
100
        return resolve(function() use($responsePromise) {
101
            /** @var HttpResponse $response */
102
            $response = yield $responsePromise;
103
104
            try {
105
                $decoded = json_try_decode($response->getBody(), true);
106
            } catch (JSONDecodeErrorException $e) {
107
                throw new RequestFailedException('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...
108
            }
109
110
            $this->throwFromErrorResponse($response, $decoded);
111
112
            return $decoded;
113
        });
114
    }
115
116 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...
117
    {
118
        $header   = $this->getHeader('POST', $request->getEndpoint(), ...$request->getParameters());
119
        $response = $this->httpClient->post($request->getEndpoint(), $header, new Body(...$request->getParameters()));
120
121
        return $this->handleResponse($response);
122
    }
123
124 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...
125
    {
126
        $header   = $this->getHeader('GET', $request->getEndpoint(), ...$request->getParameters());
127
        $response = $this->httpClient->get($request->getEndpoint(), $header, ...$request->getParameters());
128
129
        return $this->handleResponse($response);
130
    }
131
132
    private function getHeader(string $method, Url $url, Parameter ...$parameters): Header
133
    {
134
        $oauthParameters     = new Parameters($this->applicationCredentials, $this->accessToken, $url, ...$parameters);
135
        $baseSignatureString = new BaseString($method, $url, $oauthParameters);
136
        $signingKey          = new Key($this->applicationCredentials, $this->accessToken);
137
        $signature           = new Signature($baseSignatureString, $signingKey);
138
139
        return new Header($oauthParameters, $signature);
140
    }
141
}
142