Completed
Pull Request — master (#10)
by Dennis
02:26
created

Client   C

Complexity

Total Complexity 22

Size/Duplication

Total Lines 178
Duplicated Lines 10.11 %

Coupling/Cohesion

Components 2
Dependencies 20

Importance

Changes 0
Metric Value
wmc 22
lcom 2
cbo 20
dl 18
loc 178
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
A processResponse() 0 7 1
D mapResponse() 0 25 10
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
3
namespace Link0\Bunq;
4
5
use GuzzleHttp\Client as GuzzleClient;
6
use GuzzleHttp\HandlerStack;
7
use GuzzleHttp\Middleware;
8
use Link0\Bunq\Domain\Certificate;
9
use Link0\Bunq\Domain\DeviceServer;
10
use Link0\Bunq\Domain\Id;
11
use Link0\Bunq\Domain\Keypair;
12
use Link0\Bunq\Domain\Keypair\PublicKey;
13
use Link0\Bunq\Domain\MonetaryAccountBank;
14
use Link0\Bunq\Domain\Payment;
15
use Link0\Bunq\Domain\Token;
16
use Link0\Bunq\Domain\UserCompany;
17
use Link0\Bunq\Domain\UserPerson;
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
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 = [])
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 = [])
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 = [])
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|PaginatedResponse
117
     */
118
    private function processResponse(ResponseInterface $response)
119
    {
120
        $contents = (string) $response->getBody();
121
        $json = json_decode($contents, true);
122
123
        return new PaginatedResponse($this, $json);
124
    }
125
126
    public function mapResponse(string $key, array $value)
127
    {
128
        switch ($key) {
129
            case 'DeviceServer':
130
                return DeviceServer::fromArray($value);
131
            case 'MonetaryAccountBank':
132
                return MonetaryAccountBank::fromArray($value);
133
            case 'UserPerson':
134
                return UserPerson::fromArray($value);
135
            case 'UserCompany':
136
                return UserCompany::fromArray($value);
137
            case 'Id':
138
                return Id::fromInteger($value['id']);
139
            case 'CertificatePinned':
140
                return Certificate::fromArray($value);
141
            case 'Payment':
142
                return Payment::fromArray($value);
143
            case 'ServerPublicKey':
144
                return PublicKey::fromServerPublicKey($value);
145
            case 'Token':
146
                return Token::fromArray($value);
147
            default:
148
                throw new \Exception("Unknown struct type: " . $key);
149
        }
150
    }
151
152
    /**
153
     * @param string $sessionToken
154
     * @return void
155
     */
156
    private function addRequestIdMiddleware(string $sessionToken)
157
    {
158
        $this->handlerStack->push(
159
            Middleware::mapRequest(new RequestIdMiddleware($sessionToken)),
160
            'bunq_request_id'
161
        );
162
    }
163
164
    /**
165
     * @param Keypair $keypair
166
     * @return void
167
     */
168
    private function addRequestSignatureMiddleware(Keypair $keypair)
169
    {
170
        // TODO: Figure out if we can skip this middleware on POST /installation
171
        $this->handlerStack->push(
172
            Middleware::mapRequest(new RequestSignatureMiddleware($keypair->privateKey())),
173
            'bunq_request_signature'
174
        );
175
    }
176
177
    /**
178
     * @param PublicKey|null $serverPublicKey
179
     * @return void
180
     */
181
    private function addServerResponseMiddleware(PublicKey $serverPublicKey = null)
182
    {
183
        // If we have obtained the server's public key, we can verify responses
184
        if ($serverPublicKey instanceof PublicKey) {
185
            $this->handlerStack->push(
186
                Middleware::mapResponse(new ResponseSignatureMiddleware($serverPublicKey))
187
            );
188
        }
189
    }
190
191
    /**
192
     * @param Environment $environment
193
     * @return void
194
     */
195
    private function addDebugMiddleware(Environment $environment)
196
    {
197
        if ($environment->inDebugMode()) {
198
            $this->handlerStack->push(DebugMiddleware::tap(), 'debug_tap');
199
        }
200
    }
201
}
202