Completed
Push — master ( 794ec6...01bc45 )
by Andrew
06:50
created

Instance   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 80.65%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 65
ccs 25
cts 31
cp 0.8065
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A get() 0 4 1
A formPost() 0 4 1
A jsonPost() 0 4 1
A makeRequest() 0 17 2
A processResponse() 0 16 4
1
<?php
2
3
namespace NodeRED;
4
5
use GuzzleHttp\Client;
6
use Psr\Http\Message\ResponseInterface;
7
8
class Instance
9
{
10
    private $endpoint;
11
    private $client;
12
13 3
    public function __construct($endpoint, Client $client = null)
14
    {
15 3
        if (null === $client) {
16
            $client = new Client();
17
        }
18
19 3
        $this->endpoint = $endpoint;
20 3
        $this->client = $client;
21 3
    }
22
23 2
    public function get($path, $token = null)
24
    {
25 2
        return $this->makeRequest('GET', $path, [], $token);
26
    }
27
28 1
    public function formPost($path, $data, $token = null)
29
    {
30 1
        return $this->makeRequest('POST', $path, ['form_params' => $data], $token);
31
    }
32
33
    public function jsonPost($path, $data, $token = null)
34
    {
35
        return $this->makeRequest('POST', $path, ['json' => $data], $token);
36
    }
37
38 3
    private function makeRequest($method, $path, $extraOptions = [], $token = null)
39
    {
40
        $options = [
41
            'headers' => [
42 3
                'Node-RED-API-Version' => 'v2',
43 3
            ],
44 3
            'http_errors' => false,
45 3
        ];
46
47 3
        if (null !== $token) {
48
            $options['headers']['Authorization'] = $token->getAuthorizationString();
49
        }
50
51 3
        $response = $this->client->request($method, $this->endpoint . $path, array_merge($options, $extraOptions));
52
53 3
        return $this->processResponse($response);
54
    }
55
56 3
    private function processResponse(ResponseInterface $response)
57
    {
58 3
        $statusCode = $response->getStatusCode();
59
60 3
        if ($statusCode < 200 || $statusCode >= 300) {
61 1
            throw ApiException::fromResponse($response);
62
        }
63
64 2
        $json = json_decode($response->getBody(), true);
65
66 2
        if (NULL === $json) {
67 1
            throw new ApiException('Could not get JSON from response', 0, $response);
68
        }
69
70 1
        return $json;
71
    }
72
}
73