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