Api   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 55
rs 10
c 0
b 0
f 0
wmc 12

4 Methods

Rating   Name   Duplication   Size   Complexity  
A post() 0 12 2
B checkForErrorResponse() 0 14 8
A getClient() 0 3 1
A __construct() 0 3 1
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
}