Completed
Push — master ( 4e0187...f8145c )
by Andreas
02:04
created

RestClient   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 167
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 44%

Importance

Changes 0
Metric Value
wmc 22
lcom 1
cbo 7
dl 0
loc 167
ccs 33
cts 75
cp 0.44
rs 10
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A addHeader() 0 4 1
A post() 0 4 1
A put() 0 6 1
A delete() 0 6 1
A request() 0 14 1
A get() 0 17 2
A getUri() 0 12 3
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 resolveResponse() 0 13 2
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 extends AbstractClient
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 2
    public function __construct(
26
        $baseUri,
27
        $resource,
28
        array $headers = [],
29
        array $options = []
30
    ) {
31 2
        $this->baseUri = $baseUri;
32 2
        $this->headers = $headers;
33 2
        $this->options = $options;
34 2
        $this->resource = $resource;
35 2
    }
36
37
    public function addHeader($name, $value)
38
    {
39
        $this->headers[$name] = $value;
40
    }
41
42 1
    public function get($id = null, $payload = null)
43
    {
44 1
        $factory = $this->getMessageFactory();
45 1
        $uri = $this->getUri($id);
46 1
        if ($query = $this->normalizePayload($payload)) {
47 1
            $uri = $uri . '?' . ltrim($query, '?');
48
        }
49 1
        $request = $factory->createRequest(
50 1
            'GET',
51 1
            $uri,
52 1
            $this->headers
53
        );
54
55 1
        $request = $this->authenticate($request);
56
57 1
        return $this->resolveResponse($this->sendRequest($request));
58
    }
59
60
    public function post($payload)
61
    {
62
        return $this->request($this->getUri(), 'POST', $payload);
63
    }
64
65
    public function put($id, $payload = null)
66
    {
67
        $uri = $this->getUri($id);
68
69
        return $this->request($uri, 'PUT', $payload);
70
    }
71
72
    private function request($uri, $method, $payload = null)
73
    {
74
        $factory = $this->getMessageFactory();
75
        $request = $factory->createRequest(
76
            $method,
77
            $uri,
78
            $this->headers,
79
            $this->normalizePayload($payload)
80
        );
81
82
        $request = $this->authenticate($request);
83
84
        return $this->resolveResponse($this->sendRequest($request));
85
    }
86
87
    public function delete($id)
88
    {
89
        $uri = $this->getUri($id);
90
91
        return $this->request($uri, 'DELETE');
92
    }
93
94 3
    public function getUri($id = null)
95
    {
96 3
        $uri = $this->resource
97 2
            ? sprintf('%s/%s', $this->baseUri, $this->resource)
98 3
            : $this->baseUri;
99
100 3
        if ($id) {
101 1
            $uri = sprintf($uri, $id);
102
        }
103
104 3
        return $uri;
105
    }
106
107
    public function setBasicAuthentication($username, $password)
108
    {
109
        $this->username = $username;
110
        $this->pass = $password;
111
    }
112
113
    public function setHeaderAuthentication($name, $value)
114
    {
115
        $this->headerAuthentication = ['name' => $name, 'value' => $value];
116
    }
117
118 1
    protected function authenticate(RequestInterface $request)
119
    {
120 1
        if ($this->username || $this->pass) {
121
            $authentication = new BasicAuth($this->username, $this->pass);
122
123
            return $authentication->authenticate($request);
124
        }
125
126 1
        if (!empty($this->headerAuthentication)) {
127
            $request = $request->withHeader(
128
                $this->headerAuthentication['name'],
129
                $this->headerAuthentication['value']
130
            );
131
132
            return $request;
133
        }
134
135 1
        return $request;
136
    }
137
138 1
    private function normalizePayload($payload)
139
    {
140 1
        if (is_array($payload)) {
141 1
            return http_build_query($payload);
142
        }
143
144
        return $payload;
145
    }
146
147 1
    private function getMessageFactory()
148
    {
149 1
        return MessageFactoryDiscovery::find();
150
    }
151
152
    /**
153
     * Resolve the response from client.
154
     *
155
     * @param ResponseInterface $response
156
     * @return array An array with following values:
157
     *              'status': The Http status of response
158
     *              'headers': An array of response headers
159
     *              'body': The json decoded body response. (Since we are in
160
     *              RestClient)
161
     *              'raw_response': The raw body response for logging purposes.
162
     *              'raw_request': The raw body request for logging purposes.
163
     */
164
    protected function resolveResponse(ResponseInterface $response)
165
    {
166
        $body = $response->getBody()->__toString();
167
        $responseBody = json_decode($body, true) ?: [];
168
169
        return array(
170
            'status' => $response->getStatusCode(),
171
            'headers' => $response->getHeaders(),
172
            'body' => $responseBody,
173
            'raw_response' => $body,
174
            'raw_request' => $this->rawRequest,
175
        );
176
    }
177
}
178