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