Completed
Push — master ( 1f9abb...2de529 )
by Gideon
05:43
created

RestClient::doRequest()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 31
rs 8.439
cc 6
eloc 19
nc 12
nop 3
1
<?php
2
3
namespace Gidkom\OpenFireRestApi;
4
5
use GuzzleHttp\Client;
6
/**
7
* 
8
*/
9
class RestClient
10
{
11
	public $host = 'localhost';
12
    public $port = '9090';
13
    public $plugin = '/plugins/restapi/v1';
14
    public $secret = 'SuperSecret';
15
    public $useSSL = false;
16
    protected $params  = array();
17
    private $client;
18
    public $bcastRoles = array();
19
    public $useBasicAuth = false;
20
    public $basicUser = 'admin';
21
    public $basicPwd = '1234';
22
23
	function __construct()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
24
	{
25
		$this->client = new Client();
26
	}
27
28
    /**
29
     * Make the request and analyze the result
30
     *
31
     * @param   string          $type           Request method
32
     * @param   string          $endpoint       Api request endpoint
33
     * @param   array           $params         Parameters
34
     * @return  array|false                     Array with data or error, or False when something went fully wrong
35
     */
36
	protected function doRequest($type, $endpoint, $params=[])
37
    {
38
    	$base = ($this->useSSL) ? "https" : "http";
39
    	$url = $base . "://" . $this->host . ":" .$this->port.$this->plugin.$endpoint;
40
	    
41
		if ($this->useBasicAuth)
42
            $auth = 'Basic ' . base64_encode($this->basicUser . ':' . $this->basicPwd);
43
        else
44
            $auth = $this->secret;
45
	    
46
    	$headers = array(
47
  			'Accept' => 'application/json',
48
  			'Authorization' => $auth,
49
            'Content-Type'=>'application/json'
50
  		);
51
52
        $body = json_encode($params);
53
54
        try {
55
        	$result = $this->client->request($type, $url, compact('headers','body'));
56
        } catch (\Exception $e) {
57
        	return  ['status'=>false, 'data'=>['message'=>$e->getMessage()]];
58
        }
59
	        
60
        
61
        if ($result->getStatusCode() == 200 || $result->getStatusCode() == 201) {
62
            return array('status'=>true, 'data'=>json_decode($result->getBody()));
63
        }
64
        return array('status'=>false, 'data'=>json_decode($result->getBody()));
65
    	
66
    }
67
    
68
69
}