|
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() |
|
|
|
|
|
|
24
|
|
|
{ |
|
25
|
|
|
$this->client = new Client(); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function geti() |
|
29
|
|
|
{ |
|
30
|
|
|
return $this->host. ' '. $this->secret; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
|
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Make the request and analyze the result |
|
37
|
|
|
* |
|
38
|
|
|
* @param string $type Request method |
|
39
|
|
|
* @param string $endpoint Api request endpoint |
|
40
|
|
|
* @param array $params Parameters |
|
41
|
|
|
* @return array|false Array with data or error, or False when something went fully wrong |
|
42
|
|
|
*/ |
|
43
|
|
|
protected function doRequest($type, $endpoint, $params=[]) |
|
44
|
|
|
{ |
|
45
|
|
|
$base = ($this->useSSL) ? "https" : "http"; |
|
46
|
|
|
$url = $base . "://" . $this->host . ":" .$this->port.$this->plugin.$endpoint; |
|
47
|
|
|
|
|
48
|
|
|
if ($this->useBasicAuth) |
|
49
|
|
|
$auth = 'Basic ' . base64_encode($this->basicUser . ':' . $this->basicPwd); |
|
50
|
|
|
else |
|
51
|
|
|
$auth = $this->secret; |
|
52
|
|
|
|
|
53
|
|
|
$headers = array( |
|
54
|
|
|
'Accept' => 'application/json', |
|
55
|
|
|
'Authorization' => $auth |
|
56
|
|
|
); |
|
57
|
|
|
|
|
58
|
|
|
$body = json_encode($params); |
|
59
|
|
|
// $headers += ['Content-Type'=>'application/json']; |
|
|
|
|
|
|
60
|
|
|
|
|
61
|
|
|
|
|
62
|
|
|
try { |
|
63
|
|
|
$result = $this->client->request($type, $url, compact('headers','body')); |
|
64
|
|
|
} catch (Exception $e) { |
|
|
|
|
|
|
65
|
|
|
$result = $e->message; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
|
|
69
|
|
|
|
|
70
|
|
|
|
|
71
|
|
|
if ($result->getStatusCode() == 200 || $result->getStatusCode() == 201) { |
|
72
|
|
|
return array('status'=>true, 'message'=>json_decode($result->getBody())); |
|
73
|
|
|
} |
|
74
|
|
|
return array('status'=>false, 'message'=>json_decode($result->getBody())); |
|
75
|
|
|
|
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
|
|
79
|
|
|
} |
Adding explicit visibility (
private,protected, orpublic) is generally recommend to communicate to other developers how, and from where this method is intended to be used.