Completed
Push — master ( 6f25b0...3b85e4 )
by Andrew
03:45 queued 01:06
created

Instance::formPost()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 3
crap 1
1
<?php
2
3
namespace NodeRED;
4
5
use GuzzleHttp\Client;
6
7
class Instance
8
{
9
    private $endpoint;
10
    private $client;
11
12 3
    public function __construct($endpoint, Client $client = null)
13
    {
14 3
        if (null === $client) {
15
            $client = new Client();
16
        }
17
18 3
        $this->endpoint = $endpoint;
19 3
        $this->client = $client;
20 3
    }
21
22 2
    public function get($path, $token = null)
0 ignored issues
show
Unused Code introduced by
The parameter $token is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
23
    {
24 2
        return $this->makeRequest('GET', $path, [], null);
25 1
    }
26
27 1
    public function formPost($path, $data, $token = null)
28
    {
29 1
        return $this->makeRequest('POST', $path, ['form_params' => $data], $token);
30
    }
31
32
    public function jsonPost($path, $data, $token = null)
33
    {
34
        return $this->makeRequest('POST', $path, ['json' => $data], $token);
35
    }
36
37 3
    private function makeRequest($method, $path, $extraOptions = [], $token = null)
38
    {
39
        $options = [
40
            'headers' => [
41 3
                'Node-RED-API-Version' => 'v2',
42 3
            ],
43 3
            'http_errors' => false,
44 3
        ];
45
46 3
        if (null !== $token) {
47
            $options['headers']['Authorization'] = $token->getAuthorizationString();
48
        }
49
50 3
        $response = $this->client->request($method, $this->endpoint . $path, array_merge($options, $extraOptions));
51
52 3
        $statusCode = $response->getStatusCode();
53
54 3
        if ($statusCode < 200 || $statusCode >= 300) {
55 1
            throw ApiException::fromResponse($response);
56
        }
57
58 2
        $json = json_decode($response->getBody(), true);
59
60 2
        if (NULL === $json) {
61 1
            throw new ApiException('Could not get JSON from response', 0, $response);
62
        }
63
64 1
        return $json;
65
    }
66
}
67