Completed
Push — master ( 1994ca...a6fb77 )
by Andreas
03:32
created

RestClient::setHeaderAuthentication()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
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 2
    public function __construct(
26
        $baseUri,
27
        $resource,
28
        array $headers = [],
29
        array $options = []
30
    ) {
31 2
        $this->baseUri = rtrim($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
            $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 = sprintf('%s%s', $this->baseUri, $this->resource);
97
98 3
        if ($id) {
99 1
            $uri = sprintf($uri, $id);
100
        }
101
102 3
        return $uri;
103
    }
104
105
    public function setBasicAuthentication($username, $password)
106
    {
107
        $this->username = $username;
108
        $this->pass = $password;
109
    }
110
111
    public function setHeaderAuthentication($name, $value)
112
    {
113
        $this->headerAuthentication = ['name' => $name, 'value' => $value];
114
    }
115
116 1
    protected function authenticate(RequestInterface $request)
117
    {
118 1
        if ($this->username || $this->pass) {
119
            $authentication = new BasicAuth($this->username, $this->pass);
120
121
            return $authentication->authenticate($request);
122
        }
123
124 1
        if (!empty($this->headerAuthentication)) {
125
            $request = $request->withHeader(
126
                $this->headerAuthentication['name'],
127
                $this->headerAuthentication['value']
128
            );
129
130
            return $request;
131
        }
132
133 1
        return $request;
134
    }
135
136 1
    private function normalizePayload($payload)
137
    {
138 1
        if (is_array($payload)) {
139 1
            return http_build_query($payload);
140
        }
141
142
        return $payload;
143
    }
144
145 1
    private function getMessageFactory()
146
    {
147 1
        return MessageFactoryDiscovery::find();
148
    }
149
150
    /**
151
     * Resolve the response from client.
152
     *
153
     * @param ResponseInterface $response
154
     * @return array An array with following values:
155
     *              'status': The Http status of response
156
     *              'headers': An array of response headers
157
     *              'body': The json decoded body response. (Since we are in
158
     *              RestClient)
159
     *              'raw_response': The raw body response for logging purposes.
160
     *              'raw_request': The raw body request for logging purposes.
161
     */
162
    protected function resolveResponse(ResponseInterface $response)
163
    {
164
        $body = $response->getBody()->__toString();
165
        $responseBody = json_decode($body, true) ?: [];
166
167
        return array(
168
            'status' => $response->getStatusCode(),
169
            'headers' => $response->getHeaders(),
170
            'body' => $responseBody,
171
            'raw_response' => $body,
172
            'raw_request' => $this->rawRequest,
173
        );
174
    }
175
}
176