Completed
Push — master ( 96ecdf...475a08 )
by Andreas
02:03
created

RestClient::request()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 10
cp 0
rs 9.4285
c 0
b 0
f 0
nc 1
cc 1
eloc 9
nop 3
crap 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
    private $options = [];
26
27
    private $rawRequest;
28
29 2
    public function __construct(
30
        $baseUri,
31
        $resource,
32
        array $headers = [],
33
        array $options = []
34
    ) {
35 2
        $this->baseUri = rtrim($baseUri, '/') . '/';
36 2
        $this->headers = $headers;
37 2
        $this->options = $options;
38 2
        $this->resource = $resource;
39 2
    }
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 1
        $factory = $this->getMessageFactory();
49 1
        $uri = $this->getUri($id);
50 1
        if ($query = $this->normalizePayload($payload)) {
51 1
            $uri = $uri . '?' . ltrim($query, '?');
52 1
        }
53 1
        $request = $factory->createRequest(
54 1
            'GET',
55 1
            $uri,
56 1
            $this->headers
57 1
        );
58
59 1
        $request = $this->authenticate($request);
60
61 1
        return $this->resolveResponse($this->sendRequest($request));
62
    }
63
64
    public function post($payload)
65
    {
66
        return $this->request($this->getUri(), 'POST', $payload);
67
    }
68
69
    public function put($id, $payload = null)
70
    {
71
        $uri = $this->getUri($id);
72
73
        return $this->request($uri, 'PUT', $payload);
74
    }
75
76
    private function request($uri, $method, $payload = null)
77
    {
78
        $factory = $this->getMessageFactory();
79
        $request = $factory->createRequest(
80
            $method,
81
            $uri,
82
            $this->headers,
83
            $this->normalizePayload($payload)
84
        );
85
86
        $request = $this->authenticate($request);
87
88
        return $this->resolveResponse($this->sendRequest($request));
89
    }
90
91
    public function delete($id)
92
    {
93
        $uri = $this->getUri($id);
94
95
        return $this->request($uri, 'DELETE');
96
    }
97
98 3
    public function getUri($id = null)
99
    {
100 3
        $uri = sprintf('%s%s', $this->baseUri, $this->resource);
101
102 3
        if ($id) {
103 1
            $uri = sprintf($uri, $id);
104 1
        }
105
106 3
        return $uri;
107
    }
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 1
    protected function authenticate(RequestInterface $request)
121
    {
122 1
        if ($this->username || $this->pass) {
123
            $authentication = new BasicAuth($this->username, $this->pass);
124
125
            return $authentication->authenticate($request);
126
        }
127
128 1
        if (!empty($this->headerAuthentication)) {
129
            $request = $request->withHeader(
130
                $this->headerAuthentication['name'],
131
                $this->headerAuthentication['value']
132
            );
133
134
            return $request;
135
        }
136
137 1
        return $request;
138
    }
139
140 1
    private function normalizePayload($payload)
141
    {
142 1
        if (is_array($payload)) {
143 1
            return http_build_query($payload);
144
        }
145
146
        return $payload;
147
    }
148
149 1
    private function getMessageFactory()
150
    {
151 1
        return MessageFactoryDiscovery::find();
152
    }
153
154
    /**
155
     * Resolve the response from client.
156
     *
157
     * @param ResponseInterface $response
158
     * @return array An array with following values:
159
     *              'status': The Http status of response
160
     *              'headers': An array of response headers
161
     *              'body': The json decoded body response. (Since we are in
162
     *              RestClient)
163
     *              'raw_response': The raw body response for logging purposes.
164
     *              'raw_request': The raw body request for logging purposes.
165
     */
166
    protected function resolveResponse(ResponseInterface $response)
167
    {
168
        $body = $response->getBody()->__toString();
169
        $responseBody = json_decode($body, true) ?: [];
170
171
        return array(
172
            'status' => $response->getStatusCode(),
173
            'headers' => $response->getHeaders(),
174
            'body' => $responseBody,
175
            'raw_response' => $body,
176
            'raw_request' => $this->rawRequest,
177
        );
178
    }
179
}
180