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

Client   C

Complexity

Total Complexity 27

Size/Duplication

Total Lines 193
Duplicated Lines 9.33 %

Coupling/Cohesion

Components 2
Dependencies 20

Importance

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