Completed
Pull Request — master (#25)
by
unknown
02:01
created

Client   C

Complexity

Total Complexity 27

Size/Duplication

Total Lines 194
Duplicated Lines 9.28 %

Coupling/Cohesion

Components 2
Dependencies 20

Importance

Changes 0
Metric Value
wmc 27
lcom 2
cbo 20
dl 18
loc 194
rs 6.4705
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 17 1
A get() 0 8 1
A post() 9 9 1
A put() 9 9 1
A delete() 0 6 1
B processResponse() 0 20 5
C mapResponse() 0 28 11
A addRequestIdMiddleware() 0 7 1
A addRequestSignatureMiddleware() 0 8 1
A addServerResponseMiddleware() 0 9 2
A addDebugMiddleware() 0 6 2

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
2
namespace Link0\Bunq;
3
4
use GuzzleHttp\Client as GuzzleClient;
5
use GuzzleHttp\HandlerStack;
6
use GuzzleHttp\Middleware;
7
use Link0\Bunq\Domain\Certificate;
8
use Link0\Bunq\Domain\DeviceServer;
9
use Link0\Bunq\Domain\Id;
10
use Link0\Bunq\Domain\Keypair;
11
use Link0\Bunq\Domain\Keypair\PublicKey;
12
use Link0\Bunq\Domain\MonetaryAccountBank;
13
use Link0\Bunq\Domain\Payment;
14
use Link0\Bunq\Domain\Token;
15
use Link0\Bunq\Domain\UserCompany;
16
use Link0\Bunq\Domain\UserPerson;
17
use Link0\Bunq\Domain\RequestInquiry;
18
use Link0\Bunq\Middleware\DebugMiddleware;
19
use Link0\Bunq\Middleware\RequestIdMiddleware;
20
use Link0\Bunq\Middleware\RequestSignatureMiddleware;
21
use Link0\Bunq\Middleware\ResponseSignatureMiddleware;
22
use Psr\Http\Message\ResponseInterface;
23
24
final class Client
25
{
26
    /**
27
     * @var GuzzleClient
28
     */
29
    private $guzzle;
30
31
    /**
32
     * @var HandlerStack
33
     */
34
    private $handlerStack;
35
36
    /**
37
     * @param Environment $environment
38
     */
39
    public function __construct(Environment $environment, Keypair $keypair, PublicKey $serverPublicKey = null, string $sessionToken = '')
40
    {
41
        $this->handlerStack = HandlerStack::create();
42
43
        $this->addRequestIdMiddleware($sessionToken);
44
        $this->addRequestSignatureMiddleware($keypair);
45
        $this->addServerResponseMiddleware($serverPublicKey);
46
        $this->addDebugMiddleware($environment);
47
48
        $this->guzzle = new GuzzleClient([
49
            'base_uri' => $environment->endpoint(),
50
            'handler' => $this->handlerStack,
51
            'headers' => [
52
                'User-Agent' => 'Link0 Bunq API Client'
53
            ]
54
        ]);
55
    }
56
57
    /**
58
     * @param string $endpoint
59
     * @return array
60
     */
61
    public function get(string $endpoint, array $headers = []): array
62
    {
63
        return $this->processResponse(
64
            $this->guzzle->request('GET', $endpoint, [
65
                'headers' => $headers,
66
            ])
67
        );
68
    }
69
70
    /**
71
     * @param string $endpoint
72
     * @param array $body
73
     * @param array $headers
74
     * @return array
75
     */
76 View Code Duplication
    public function post(string $endpoint, array $body, array $headers = []): array
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...
77
    {
78
        return $this->processResponse(
79
            $this->guzzle->request('POST', $endpoint, [
80
                'json' => $body,
81
                'headers' => $headers,
82
            ])
83
        );
84
    }
85
86
    /**
87
     * @param string $endpoint
88
     * @param array $body
89
     * @param array $headers
90
     * @return array
91
     */
92 View Code Duplication
    public function put(string $endpoint, array $body, array $headers = []): array
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...
93
    {
94
        return $this->processResponse(
95
            $this->guzzle->request('PUT', $endpoint, [
96
                'json' => $body,
97
                'headers' => $headers,
98
            ])
99
        );
100
    }
101
102
    /**
103
     * @param string $endpoint
104
     * @param array $headers
105
     * @return void
106
     */
107
    public function delete(string $endpoint, array $headers = [])
108
    {
109
        $this->guzzle->request('DELETE', $endpoint, [
110
            'headers' => $headers,
111
        ]);
112
    }
113
114
    /**
115
     * @param ResponseInterface $response
116
     * @return array
117
     */
118
    private function processResponse(ResponseInterface $response): array
119
    {
120
        $contents = (string) $response->getBody();
121
        $json = json_decode($contents, true)['Response'];
122
123
        // Return empty responses
124
        if (count($json) === 0) {
125
            return [];
126
        }
127
128
        foreach ($json as $key => $value) {
129
            if (is_numeric($key)) {
130
                // Often only a single associative entry here
131
                foreach ($value as $type => $struct) {
132
                    $json[$key] = $this->mapResponse($type, $struct);
133
                }
134
            }
135
        }
136
        return $json;
137
    }
138
139
    private function mapResponse(string $key, array $value)
140
    {
141
        switch ($key) {
142
            case 'DeviceServer':
143
                return DeviceServer::fromArray($value);
144
            case 'MonetaryAccountBank':
145
                return MonetaryAccountBank::fromArray($value);
146
            case 'UserPerson':
147
                return UserPerson::fromArray($value);
148
            case 'UserCompany':
149
                return UserCompany::fromArray($value);
150
            case 'Id':
151
                return Id::fromInteger($value['id']);
152
            case 'CertificatePinned':
153
                return Certificate::fromArray($value);
154
            case 'Payment':
155
                return Payment::fromArray($value);
156
            case 'ServerPublicKey':
157
                return PublicKey::fromServerPublicKey($value);
158
            case 'Token':
159
                return Token::fromArray($value);
160
            case 'RequestInquiry':
161
                return RequestInquiry::fromArray($value);
162
                return $value;
0 ignored issues
show
Unused Code introduced by
return $value; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
163
            default:
164
                throw new \Exception("Unknown struct type: " . $key);
165
        }
166
    }
167
168
    /**
169
     * @param string $sessionToken
170
     * @return void
171
     */
172
    private function addRequestIdMiddleware(string $sessionToken)
173
    {
174
        $this->handlerStack->push(
175
            Middleware::mapRequest(new RequestIdMiddleware($sessionToken)),
176
            'bunq_request_id'
177
        );
178
    }
179
180
    /**
181
     * @param Keypair $keypair
182
     * @return void
183
     */
184
    private function addRequestSignatureMiddleware(Keypair $keypair)
185
    {
186
        // TODO: Figure out if we can skip this middleware on POST /installation
187
        $this->handlerStack->push(
188
            Middleware::mapRequest(new RequestSignatureMiddleware($keypair->privateKey())),
189
            'bunq_request_signature'
190
        );
191
    }
192
193
    /**
194
     * @param PublicKey|null $serverPublicKey
195
     * @return void
196
     */
197
    private function addServerResponseMiddleware(PublicKey $serverPublicKey = null)
198
    {
199
        // If we have obtained the server's public key, we can verify responses
200
        if ($serverPublicKey instanceof PublicKey) {
201
            $this->handlerStack->push(
202
                Middleware::mapResponse(new ResponseSignatureMiddleware($serverPublicKey))
203
            );
204
        }
205
    }
206
207
    /**
208
     * @param Environment $environment
209
     * @return void
210
     */
211
    private function addDebugMiddleware(Environment $environment)
212
    {
213
        if ($environment->inDebugMode()) {
214
            $this->handlerStack->push(DebugMiddleware::tap(), 'debug_tap');
215
        }
216
    }
217
}
218