1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace mattvb91\TronTrx; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client; |
6
|
|
|
use mattvb91\TronTrx\Exceptions\TronErrorException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class Api |
10
|
|
|
* @package mattvb91\TronTrx |
11
|
|
|
*/ |
12
|
|
|
class Api |
13
|
|
|
{ |
14
|
|
|
private $_client; |
15
|
|
|
|
16
|
|
|
public function __construct(Client $client) |
17
|
|
|
{ |
18
|
|
|
$this->_client = $client; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function getClient(): Client |
22
|
|
|
{ |
23
|
|
|
return $this->_client; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Abstracts some common functionality like formatting the post data |
28
|
|
|
* along with error handling. |
29
|
|
|
* |
30
|
|
|
* @throws TronErrorException |
31
|
|
|
*/ |
32
|
|
|
public function post(string $endpoint, array $data = [], bool $returnAssoc = false) |
33
|
|
|
{ |
34
|
|
|
if (sizeof($data)) { |
35
|
|
|
$data = ['json' => $data]; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$stream = (string)$this->getClient()->post($endpoint, $data)->getBody(); |
39
|
|
|
$body = json_decode($stream, $returnAssoc); |
40
|
|
|
|
41
|
|
|
$this->checkForErrorResponse($returnAssoc, $body); |
42
|
|
|
|
43
|
|
|
return $body; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Check if the response has an error and throw it. |
48
|
|
|
* |
49
|
|
|
* @param bool $returnAssoc |
50
|
|
|
* @param $body |
51
|
|
|
* @throws TronErrorException |
52
|
|
|
*/ |
53
|
|
|
private function checkForErrorResponse(bool $returnAssoc, $body) |
54
|
|
|
{ |
55
|
|
|
if ($returnAssoc) { |
56
|
|
|
if (isset($body['Error'])) { |
57
|
|
|
throw new TronErrorException($body['Error']); |
58
|
|
|
} elseif (isset($body['code']) && isset($body['message'])) { |
59
|
|
|
throw new TronErrorException($body['code'] . ': ' . hex2bin($body['message'])); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if (isset($body->Error)) { |
64
|
|
|
throw new TronErrorException($body->Error); |
65
|
|
|
} elseif (isset($body->code) && isset($body->message)) { |
66
|
|
|
throw new TronErrorException($body->code . ': ' . hex2bin($body->message)); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |