-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMoneyBirdClient.php
More file actions
334 lines (309 loc) · 10.8 KB
/
MoneyBirdClient.php
File metadata and controls
334 lines (309 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
<?php
namespace emilebons\moneybird;
use Exception;
class MoneyBirdClient
{
const CONTENT_TYPE_JSON = 'json'; // JSON format
const CONTENT_TYPE_URLENCODED = 'urlencoded'; // urlencoded query string, like name1=value1&name2=value2
const CONTENT_TYPE_XML = 'xml'; // XML format
const CONTENT_TYPE_AUTO = 'auto'; // attempts to determine format automatically
/**
* @var array cURL request options. Option values from this field will overwrite corresponding
* values from [[defaultCurlOptions()]].
*/
private $_curlOptions = [];
/**
* @var string API base URL.
*/
public $apiBaseUrl;
/**
* @var string the API token, i.e. "84ec207ad0154a508f798e615a998ac1fd752926d00f955fb1df3e144cba44ab"
*/
public $apiToken;
/**
* @param string $apiToken the API token to use
* @throws Exception when the API token is not set
*/
public function __construct($apiToken)
{
if(empty($apiToken)) {
throw new Exception('An API token is not provided, this is required when using MoneyBirdClient');
}
$this->apiToken = $apiToken;
}
/**
* Adds the API token authorization header to the set of headers provided
* @param array $headers the headers already provided
* @return array $headers the original headers with the authorization header added
*/
protected function addAuthorizationHeader(array $headers)
{
$headers[] = 'Authorization: Bearer '.$this->apiToken;
return $headers;
}
/**
* Performs request to the OAuth API.
* @param string $apiSubUrl API sub URL, which will be append to [[apiBaseUrl]], or absolute API URL.
* @param string $method request method.
* @param array $params request parameters.
* @param array $headers additional request headers.
* @return array API response
*/
public function api($apiSubUrl, $method = 'GET', array $params = [], array $headers = [])
{
if (preg_match('/^https?:\\/\\//is', $apiSubUrl)) {
$url = $apiSubUrl;
} else {
$url = $this->apiBaseUrl . '/' . $apiSubUrl;
}
return $this->apiInternal($url, $method, $params, $headers);
}
/**
* @inheritdoc
*/
protected function apiInternal($url, $method, array $params, array $headers)
{
return $this->sendRequest($method, $url, $params, $headers);
}
/**
* Composes HTTP request CUrl options, which will be merged with the default ones.
* @param string $method request type.
* @param string $url request URL.
* @param array $params request params.
* @return array CUrl options.
* @throws Exception on failure.
*/
protected function composeRequestCurlOptions($method, $url, array $params)
{
$curlOptions = [];
switch ($method) {
case 'GET': {
$curlOptions[CURLOPT_URL] = $this->composeUrl($url, $params);
break;
}
case 'POST': {
$curlOptions[CURLOPT_POST] = true;
$curlOptions[CURLOPT_HTTPHEADER] = ['Content-type: application/x-www-form-urlencoded'];
$curlOptions[CURLOPT_POSTFIELDS] = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
break;
}
case 'HEAD': {
$curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
if (!empty($params)) {
$curlOptions[CURLOPT_URL] = $this->composeUrl($url, $params);
}
break;
}
default: {
$curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
if (!empty($params)) {
$curlOptions[CURLOPT_POSTFIELDS] = $params;
}
}
}
return $curlOptions;
}
/**
* Composes URL from base URL and GET params.
* @param string $url base URL.
* @param array $params GET params.
* @return string composed URL.
*/
protected function composeUrl($url, array $params = [])
{
if (strpos($url, '?') === false) {
$url .= '?';
} else {
$url .= '&';
}
$url .= http_build_query($params, '', '&', PHP_QUERY_RFC3986);
return $url;
}
/**
* Converts XML document to array.
* @param string|\SimpleXMLElement $xml xml to process.
* @return array XML array representation.
*/
protected function convertXmlToArray($xml)
{
if (!is_object($xml)) {
$xml = simplexml_load_string($xml);
}
$result = (array) $xml;
foreach ($result as $key => $value) {
if (is_object($value)) {
$result[$key] = $this->convertXmlToArray($value);
}
}
return $result;
}
/**
* Returns default cURL options.
* @return array cURL options.
*/
protected function defaultCurlOptions()
{
return [
CURLOPT_USERAGENT => 'MoneyBirdClient',
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => false,
];
}
/**
* Attempts to determine HTTP request content type by headers.
* @param array $headers request headers.
* @return string content type.
*/
protected function determineContentTypeByHeaders(array $headers)
{
if (isset($headers['content_type'])) {
if (stripos($headers['content_type'], 'json') !== false) {
return self::CONTENT_TYPE_JSON;
}
if (stripos($headers['content_type'], 'urlencoded') !== false) {
return self::CONTENT_TYPE_URLENCODED;
}
if (stripos($headers['content_type'], 'xml') !== false) {
return self::CONTENT_TYPE_XML;
}
}
return self::CONTENT_TYPE_AUTO;
}
/**
* Attempts to determine the content type from raw content.
* @param string $rawContent raw response content.
* @return string response type.
*/
protected function determineContentTypeByRaw($rawContent)
{
if (preg_match('/^\\{.*\\}$/is', $rawContent)) {
return self::CONTENT_TYPE_JSON;
}
if (preg_match('/^[^=|^&]+=[^=|^&]+(&[^=|^&]+=[^=|^&]+)*$/is', $rawContent)) {
return self::CONTENT_TYPE_URLENCODED;
}
if (preg_match('/^<.*>$/is', $rawContent)) {
return self::CONTENT_TYPE_XML;
}
return self::CONTENT_TYPE_AUTO;
}
/**
* @return array cURL options.
*/
public function getCurlOptions()
{
return $this->_curlOptions;
}
/**
* @param array $curlOptions cURL options.
*/
public function setCurlOptions(array $curlOptions)
{
$this->_curlOptions = $curlOptions;
}
/**
* Merge CUrl options.
* If each options array has an element with the same key value, the latter
* will overwrite the former.
* @param array $options1 options to be merged to.
* @param array $options2 options to be merged from. You can specify additional
* arrays via third argument, fourth argument etc.
* @return array merged options (the original options are not changed.)
*/
protected function mergeCurlOptions($options1, $options2)
{
$args = func_get_args();
$res = array_shift($args);
while (!empty($args)) {
$next = array_shift($args);
foreach ($next as $k => $v) {
if (is_array($v) && !empty($res[$k]) && is_array($res[$k])) {
$res[$k] = array_merge($res[$k], $v);
} else {
$res[$k] = $v;
}
}
}
return $res;
}
/**
* Processes raw response converting it to actual data.
* @param string $rawResponse raw response.
* @param string $contentType response content type.
* @throws Exception on failure.
* @return array actual response.
*/
protected function processResponse($rawResponse, $contentType = self::CONTENT_TYPE_AUTO)
{
if (empty($rawResponse)) {
return [];
}
switch ($contentType) {
case self::CONTENT_TYPE_AUTO: {
$contentType = $this->determineContentTypeByRaw($rawResponse);
if ($contentType == self::CONTENT_TYPE_AUTO) {
throw new Exception('Unable to determine response content type automatically.');
}
$response = $this->processResponse($rawResponse, $contentType);
break;
}
case self::CONTENT_TYPE_JSON: {
$response = json_decode((string) $rawResponse, true);
break;
}
case self::CONTENT_TYPE_URLENCODED: {
$response = [];
parse_str($rawResponse, $response);
break;
}
case self::CONTENT_TYPE_XML: {
$response = $this->convertXmlToArray($rawResponse);
break;
}
default: {
throw new Exception('Unknown response type "' . $contentType . '".');
}
}
return $response;
}
/**
* Sends HTTP request.
* @param string $method request type.
* @param string $url request URL.
* @param array $params request params.
* @param array $headers additional request headers.
* @return array response.
* @throws Exception on failure.
*/
protected function sendRequest($method, $url, array $params = [], array $headers = [])
{
$curlOptions = $this->mergeCurlOptions(
$this->defaultCurlOptions(),
$this->getCurlOptions(),
[
CURLOPT_HTTPHEADER => $this->addAuthorizationHeader($headers),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $url,
],
$this->composeRequestCurlOptions(strtoupper($method), $url, $params)
);
$curlResource = curl_init();
foreach ($curlOptions as $option => $value) {
curl_setopt($curlResource, $option, $value);
}
$response = curl_exec($curlResource);
$responseHeaders = curl_getinfo($curlResource);
// check cURL error
$errorNumber = curl_errno($curlResource);
$errorMessage = curl_error($curlResource);
curl_close($curlResource);
if($errorNumber > 0) {
throw new Exception('Curl error requesting "'. $url.'": #'.$errorNumber.' - '.$errorMessage);
}
if(strncmp($responseHeaders['http_code'], '20', 2) !== 0) {
throw new Exception('Request failed with code: '.$responseHeaders['http_code'].', message: '.$response);
}
return $this->processResponse($response, $this->determineContentTypeByHeaders($responseHeaders));
}
}