1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LPTracker; |
4
|
|
|
|
5
|
|
|
use anlutro\cURL\cURL; |
6
|
|
|
use anlutro\cURL\Request; |
7
|
|
|
use LPTracker\authentication\AccessToken; |
8
|
|
|
use LPTracker\exceptions\LPTrackerResponseException; |
9
|
|
|
use LPTracker\exceptions\LPTrackerServerException; |
10
|
|
|
|
11
|
|
|
class LPTrackerRequest |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @param string $actionUrl |
15
|
|
|
* @param array $data |
16
|
|
|
* @param string $method |
17
|
|
|
* @param AccessToken|null $token |
18
|
|
|
* @param string $baseUrl |
19
|
|
|
* @return mixed |
20
|
|
|
* @throws LPTrackerResponseException |
21
|
|
|
* @throws LPTrackerServerException |
22
|
|
|
*/ |
23
|
|
|
public static function sendRequest( |
24
|
|
|
$actionUrl, |
25
|
|
|
array $data = [], |
26
|
|
|
$method = 'GET', |
27
|
|
|
AccessToken $token = null, |
28
|
|
|
$baseUrl = '' |
29
|
|
|
) { |
30
|
|
|
if (empty($baseUrl)) { |
31
|
|
|
$baseUrl = LPTrackerBase::DEFAULT_ADDRESS; |
32
|
|
|
} |
33
|
|
|
$url = $baseUrl . $actionUrl; |
34
|
|
|
$curl = new cURL(); |
35
|
|
|
$request = $curl->newRequest($method, $url, $data, Request::ENCODING_JSON); |
36
|
|
|
$request->setHeader('Content-Type', 'application/json'); |
37
|
|
|
if ($token instanceof AccessToken) { |
38
|
|
|
$request->setHeader('token', $token->getValue()); |
39
|
|
|
} |
40
|
|
|
$response = $request->send(); |
41
|
|
|
if ($response === false) { |
42
|
|
|
throw new LPTrackerServerException('Can`t get response from server'); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$body = json_decode($response->body, true); |
46
|
|
|
if ($body === false) { |
47
|
|
|
throw new LPTrackerServerException('Can`t decode response'); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if (!empty($body['errors'])) { |
51
|
|
|
if (!empty($body['errors'][0]['message'])) { |
52
|
|
|
throw new LPTrackerResponseException($body['errors'][0]['message']); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
throw new LPTrackerResponseException($body['errors'][0]); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if (empty($body['status']) || $body['status'] !== 'success') { |
59
|
|
|
throw new LPTrackerResponseException('Unknown response error'); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return isset($body['result']) ? $body['result'] : null; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|