Passed
Push — master ( 7067f6...c51298 )
by Julien
01:15 queued 11s
created

RestClient   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 292
Duplicated Lines 0 %

Test Coverage

Coverage 97.37%

Importance

Changes 0
Metric Value
dl 0
loc 292
ccs 74
cts 76
cp 0.9737
rs 9.3999
c 0
b 0
f 0
wmc 33

13 Methods

Rating   Name   Duplication   Size   Complexity  
A getCurrentRequest() 0 7 2
A getRequestHistory() 0 3 1
A setCurrentRequest() 0 5 1
A delete() 0 8 3
A logRequest() 0 13 3
C executeRequest() 0 35 7
A isHistoryLogged() 0 3 1
A get() 0 12 4
A post() 0 9 3
A __construct() 0 6 2
A mergeDefaultParameters() 0 15 2
A setLogHistory() 0 5 1
A put() 0 10 3
1
<?php
2
3
namespace Mapado\RestClientSdk;
4
5
use GuzzleHttp\ClientInterface;
6
use GuzzleHttp\Exception\ClientException;
7
use GuzzleHttp\Exception\TransferException;
8
use Mapado\RestClientSdk\Exception\RestClientException;
9
use Mapado\RestClientSdk\Exception\RestException;
10
use Psr\Http\Message\ResponseInterface;
11
use Symfony\Component\HttpFoundation\Request;
12
13
/**
14
 * Class RestClient
15
 * @author Julien Deniau <[email protected]>
16
 */
17
class RestClient
18
{
19
    /**
20
     * httpClient
21
     *
22
     * @var ClientInterface
23
     * @access private
24
     */
25
    private $httpClient;
26
27
    /**
28
     * baseUrl
29
     *
30
     * @var string
31
     * @access private
32
     */
33
    private $baseUrl;
34
35
    /**
36
     * logHistory
37
     *
38
     * @var boolean
39
     * @access private
40
     */
41
    private $logHistory;
42
43
    /**
44
     * requestHistory
45
     *
46
     * @var array
47
     * @access private
48
     */
49
    private $requestHistory;
50
51
    /**
52
     * currentRequest
53
     *
54
     * @var Request
55
     * @access private
56
     */
57
    private $currentRequest;
58
59
    /**
60
     * @param ClientInterface $httpClient
61
     * @param string|null     $baseUrl
62
     */
63
    public function __construct(ClientInterface $httpClient, $baseUrl = null)
64
    {
65 1
        $this->httpClient     = $httpClient;
66 1
        $this->baseUrl        = substr($baseUrl, -1) === '/' ? substr($baseUrl, 0, -1) : $baseUrl;
67 1
        $this->logHistory     = false;
68 1
        $this->requestHistory = [];
69 1
    }
70
71
    /**
72
     * @return bool
73
     */
74
    public function isHistoryLogged()
75
    {
76 1
        return $this->logHistory;
77
    }
78
79
    /**
80
     * setCurrentRequest
81
     *
82
     * @param Request $currentRequest
83
     * @access public
84
     * @return RestClient
85
     */
86
    public function setCurrentRequest(Request $currentRequest)
87
    {
88
        $this->currentRequest = $currentRequest;
89
90
        return $this;
91
    }
92
93
    /**
94
     * setLogHistory
95
     *
96
     * @param boolean $logHistory
97
     * @access public
98
     * @return RestClient
99
     */
100
    public function setLogHistory($logHistory)
101
    {
102 1
        $this->logHistory = $logHistory;
103
104 1
        return $this;
105
    }
106
107
    /**
108
     * @return array
109
     */
110
    public function getRequestHistory()
111
    {
112 1
        return $this->requestHistory;
113
    }
114
115
    /**
116
     * get a path
117
     *
118
     * @param string $path
119
     * @param array  $parameters
120
     * @return array|ResponseInterface|null
121
     * @throws RestException
122
     */
123
    public function get($path, $parameters = [])
124
    {
125 1
        $requestUrl = $this->baseUrl . $path;
126
        try {
127 1
            return $this->executeRequest('GET', $requestUrl, $parameters);
128 1
        } catch (ClientException $e) {
129 1
            if ($e->getResponse()->getStatusCode() === 404) {
130 1
                return null;
131
            }
132 1
            throw new RestClientException('Error while getting resource', $path, [], 7, $e);
133 1
        } catch (TransferException $e) {
134 1
            throw new RestException('Error while getting resource', $path, [], 1, $e);
135
        }
136
    }
137
138
    /**
139
     * delete
140
     *
141
     * @param string $path
142
     * @access public
143
     * @return void
144
     * @throws RestException
145
     */
146
    public function delete($path)
147
    {
148
        try {
149 1
            $this->executeRequest('DELETE', $this->baseUrl . $path);
150 1
        } catch (ClientException $e) {
151 1
            return;
152 1
        } catch (TransferException $e) {
153 1
            throw new RestException('Error while deleting resource', $path, [], 2, $e);
154
        }
155 1
    }
156
157
    /**
158
     * @param string $path
159
     * @param mixed  $data
160
     * @param array  $parameters
161
     * @return array|ResponseInterface
162
     * @throws RestClientException
163
     * @throws RestException
164
     */
165
    public function post($path, $data, $parameters = [])
166
    {
167 1
        $parameters['json'] = $data;
168
        try {
169 1
            return $this->executeRequest('POST', $this->baseUrl . $path, $parameters);
170 1
        } catch (ClientException $e) {
171 1
            throw new RestClientException('Cannot create resource', $path, [], 3, $e);
172 1
        } catch (TransferException $e) {
173 1
            throw new RestException('Error while posting resource', $path, [], 4, $e);
174
        }
175
    }
176
177
    /**
178
     * @param string $path
179
     * @param mixed  $data
180
     * @param array  $parameters
181
     * @return array|ResponseInterface
182
     * @throws RestClientException
183
     * @throws RestException
184
     */
185
    public function put($path, $data, $parameters = [])
186
    {
187 1
        $parameters['json'] = $data;
188
189
        try {
190 1
            return $this->executeRequest('PUT', $this->baseUrl . $path, $parameters);
191 1
        } catch (ClientException $e) {
192 1
            throw new RestClientException('Cannot update resource', $path, [], 5, $e);
193 1
        } catch (TransferException $e) {
194 1
            throw new RestException('Error while puting resource', $path, [], 6, $e);
195
        }
196
    }
197
198
    /**
199
     * Merge default parameters.
200
     *
201
     * @param array $parameters
202
     * @access protected
203
     * @return array
204
     */
205
    protected function mergeDefaultParameters(array $parameters)
206
    {
207 1
        $request = $this->getCurrentRequest();
208
209
        $defaultParameters = [
210 1
            'version' => '1.0',
211
        ];
212
213 1
        if ($request) {
0 ignored issues
show
introduced by
$request is of type Symfony\Component\HttpFoundation\Request, thus it always evaluated to true.
Loading history...
214 1
            $defaultParameters['headers'] = [
215 1
                'Referer' => $request->getUri(),
216
            ];
217
        }
218
219 1
        return array_replace_recursive($defaultParameters, $parameters);
220
    }
221
222
    /**
223
     * getCurrentRequest
224
     *
225
     * @access private
226
     * @return Request
227
     */
228
    protected function getCurrentRequest()
229
    {
230 1
        if (!$this->currentRequest) {
231 1
            $this->currentRequest = Request::createFromGlobals();
232
        }
233
234 1
        return $this->currentRequest;
235
    }
236
237
    /**
238
     * Executes request.
239
     *
240
     * @param string $method
241
     * @param string $url
242
     * @param array  $parameters
243
     * @access private
244
     * @return ResponseInterface|array
245
     * @throws TransferException
246
     */
247
    private function executeRequest($method, $url, $parameters = [])
248
    {
249 1
        $parameters = $this->mergeDefaultParameters($parameters);
250
251 1
        $startTime = null;
252 1
        if ($this->isHistoryLogged()) {
253 1
            $startTime = microtime(true);
254
        }
255
256
        try {
257 1
            $response = $this->httpClient->request($method, $url, $parameters);
258 1
            $this->logRequest($startTime, $method, $url, $parameters, $response);
259 1
        } catch (TransferException $e) {
260 1
            $this->logRequest($startTime, $method, $url, $parameters);
261 1
            throw $e;
262
        }
263
264 1
        $headers = $response->getHeaders();
265 1
        $jsonContentTypeList = ['application/ld+json', 'application/json'];
266
267 1
        $requestIsJson = false;
268
269 1
        if (isset($headers['Content-Type'])) {
270 1
            foreach ($jsonContentTypeList as $contentType) {
271 1
                if (stripos($headers['Content-Type'][0], $contentType) !== false) {
272 1
                    $requestIsJson = true;
273 1
                    break;
274
                }
275
            }
276
        }
277
278 1
        if ($requestIsJson) {
279 1
            return json_decode($response->getBody(), true);
280
        } else {
281 1
            return $response;
282
        }
283
    }
284
285
    /**
286
     * Logs request.
287
     *
288
     * @param float|null             $startTime
289
     * @param string                 $method
290
     * @param string                 $url
291
     * @param array                  $parameters
292
     * @param ResponseInterface|null $response
293
     * @access private
294
     * @return void
295
     */
296
    private function logRequest($startTime, $method, $url, $parameters, ResponseInterface $response = null)
297
    {
298 1
        if ($this->isHistoryLogged()) {
299 1
            $queryTime = microtime(true) - $startTime;
300
301 1
            $this->requestHistory[] = [
302 1
                'method'       => $method,
303 1
                'url'          => $url,
304 1
                'parameters'   => $parameters,
305 1
                'response'     => $response,
306 1
                'responseBody' => $response ? json_decode($response->getBody(), true) : null,
307 1
                'queryTime'    => $queryTime,
308 1
                'backtrace'    => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS),
309
            ];
310
        }
311 1
    }
312
}
313