Passed
Push — master ( 2d592f...824abc )
by Dennis
30s
created

Client::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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