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

Instance::processResponse()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 9.2
cc 4
eloc 8
nc 3
nop 1
crap 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