Completed
Push — master ( 60aec0...f632bc )
by Andreas
12:47 queued 10:41
created

RestClient   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 188
Duplicated Lines 21.81 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 84.21%

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 8
dl 41
loc 188
ccs 16
cts 19
cp 0.8421
rs 10
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A addHeader() 0 4 1
A get() 0 17 2
A post() 14 14 1
A put() 14 14 1
A delete() 0 3 1
A getUri() 0 10 2
A setBasicAuthentication() 0 5 1
A setHeaderAuthentication() 0 4 1
A authenticate() 0 19 4
A normalizePayload() 0 8 2
A getMessageFactory() 0 4 1
A discoverClient() 0 4 1
A sendRequest() 13 13 2
A resolveResponse() 0 13 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 Larium\Pay\Client;
4
5
use Psr\Http\Message\RequestInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Http\Discovery\HttpClientDiscovery;
8
use Http\Message\Authentication\BasicAuth;
9
use Http\Discovery\MessageFactoryDiscovery;
10
11
class RestClient
12
{
13
    private $baseUri;
14
15
    private $resource;
16
17
    private $username;
18
19
    private $pass;
20
21
    private $headerAuthentication = [];
22
23
    private $headers = [];
24
25
    private $options = [];
26
27
    private $rawRequest;
28
29 1
    public function __construct(
30
        $baseUri,
31
        $resource,
32 1
        array $headers = [],
33 1
        array $options = []
34
    ) {
35
        $this->baseUri = rtrim($baseUri, '/') . '/';
36 1
        $this->headers = $headers;
37 1
        $this->options = $options;
38 1
        $this->resource = $resource;
39
    }
40
41
    public function addHeader($name, $value)
42
    {
43
        $this->headers[$name] = $value;
44
    }
45
46 1
    public function get($id = null, $payload = null)
47
    {
48
        $factory = $this->getMessageFactory();
49
        $uri = $this->getUri($id);
50
        if ($query = $this->normalizePayload($payload)) {
51
            $uri = $uri . '?' . ltrim($query, '?');
52
        }
53
        $request = $factory->createRequest(
54 1
            'GET',
55
            $uri,
56 1
            $this->headers
57
        );
58
59
        $request = $this->authenticate($request);
60
61
        return $this->resolveResponse($this->sendRequest($request));
62
    }
63
64 View Code Duplication
    public function post($payload)
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...
65
    {
66
        $factory = $this->getMessageFactory();
67
        $request = $factory->createRequest(
68
            'POST',
69
            $this->getUri(),
70
            $this->headers,
71
            $this->normalizePayload($payload)
72
        );
73
74
        $request = $this->authenticate($request);
75
76
        return $this->resolveResponse($this->sendRequest($request));
77
    }
78
79 View Code Duplication
    public function put($id, $payload = null)
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...
80
    {
81
        $factory = $this->getMessageFactory();
82
        $request = $factory->createRequest(
83
            'PUT',
84
            $this->getUri($id),
85
            $this->headers,
86
            $this->normalizePayload($payload)
87
        );
88
89
        $request = $this->authenticate($request);
90
91
        return $this->resolveResponse($this->sendRequest($request));
92
    }
93
94
    public function delete($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
95
    {
96
    }
97
98 2
    public function getUri($id = null)
99
    {
100
        $uri = sprintf('%s%s', $this->baseUri, $this->resource);
101
102 2
        if ($id) {
103
            $uri = sprintf($uri, $id);
104
        }
105
106 2
        return $uri;
107 1
    }
108
109
    public function setBasicAuthentication($username, $password)
110
    {
111
        $this->username = $username;
112
        $this->pass = $password;
113
    }
114
115
    public function setHeaderAuthentication($name, $value)
116
    {
117
        $this->headerAuthentication = ['name' => $name, 'value' => $value];
118
    }
119
120
    private function authenticate(RequestInterface $request)
121
    {
122
        if ($this->username || $this->pass) {
123
            $authentication = new BasicAuth($this->username, $this->pass);
124
125
            return $authentication->authenticate($request);
126
        }
127
128
        if (!empty($this->headerAuthentication)) {
129
            $request = $request->withHeader(
130
                $this->headerAuthentication['name'],
131
                $this->headerAuthentication['value']
132
            );
133
134
            return $request;
135
        }
136
137
        return $request;
138
    }
139
140
    private function normalizePayload($payload)
141
    {
142
        if (is_array($payload)) {
143
            return http_build_query($payload);
144
        }
145
146
        return $payload;
147
    }
148
149
    private function getMessageFactory()
150
    {
151
        return MessageFactoryDiscovery::find();
152
    }
153
154
    protected function discoverClient()
155
    {
156
        return HttpClientDiscovery::find();
157
    }
158
159 1 View Code Duplication
    private function sendRequest(RequestInterface $request)
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...
160
    {
161
        $request = $this->authenticate($request);
162
163
        $response = $this->discoverClient()->sendRequest($request);
164
165
        if ($request->getBody()->isSeekable()) {
166
            $request->getBody()->rewind();
167
        }
168
        $this->rawRequest = $request->getBody()->__toString();
169
170 1
        return $response;
171 1
    }
172
173
    /**
174
     * Resolve the response from client.
175
     *
176
     * @param ResponseInterface $response
177
     * @return array An array with following values:
178
     *              'status': The Http status of response
179
     *              'headers': An array of response headers
180
     *              'body': The json decoded body response. (Since we are in
181
     *              RestClient)
182
     *              'raw_response': The raw body response for logging purposes.
183
     *              'raw_request': The raw body request for logging purposes.
184
     */
185
    protected function resolveResponse(ResponseInterface $response)
186
    {
187
        $body = $response->getBody()->__toString();
188
        $responseBody = json_decode($body, true) ?: [];
189
190
        return array(
191
            'status' => $response->getStatusCode(),
192
            'headers' => $response->getHeaders(),
193
            'body' => $responseBody,
194
            'raw_response' => $body,
195
            'raw_request' => $this->rawRequest,
196
        );
197
    }
198
}
199