1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Brofist\ApiClient; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client as HttpClient; |
6
|
|
|
|
7
|
|
|
class Json implements JsonInterface |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var HttpClient |
11
|
|
|
*/ |
12
|
|
|
private $httpClient; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var string |
16
|
|
|
*/ |
17
|
|
|
private $endpoint = ''; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
private $additionalOptions = []; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param array $options |
26
|
|
|
*/ |
27
|
10 |
|
public function __construct(array $options = []) |
28
|
|
|
{ |
29
|
10 |
|
if (!isset($options['endpoint'])) { |
30
|
1 |
|
throw new \InvalidArgumentException("Endpoint not set"); |
31
|
|
|
} |
32
|
|
|
|
33
|
10 |
|
$this->endpoint = trim($options['endpoint'], '/'); |
34
|
|
|
|
35
|
10 |
|
if (isset($options['authToken'])) { |
36
|
1 |
|
$this->additionalOptions['auth'] = [$options['authToken'], '']; |
37
|
1 |
|
} |
38
|
|
|
|
39
|
10 |
|
if (isset($options['basicAuth'])) { |
40
|
1 |
|
$this->additionalOptions['auth'] = $options['basicAuth']; |
41
|
1 |
|
} |
42
|
|
|
|
43
|
10 |
|
if (!isset($options['httpClient'])) { |
44
|
1 |
|
$options['httpClient'] = new HttpClient(); |
45
|
1 |
|
} |
46
|
|
|
|
47
|
10 |
|
$this->httpClient = $options['httpClient']; |
48
|
10 |
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @return string |
52
|
|
|
*/ |
53
|
1 |
|
public function getEndpoint() |
54
|
|
|
{ |
55
|
1 |
|
return $this->endpoint; |
56
|
|
|
} |
57
|
|
|
|
58
|
3 |
|
public function get($path, array $params = []) |
59
|
|
|
{ |
60
|
3 |
|
return $this->request('GET', $path, ['query' => $params]); |
61
|
|
|
} |
62
|
|
|
|
63
|
2 |
|
public function post($path, array $postData = []) |
64
|
|
|
{ |
65
|
2 |
|
return $this->request('POST', $path, ['form_params' => $postData]); |
66
|
|
|
} |
67
|
|
|
|
68
|
1 |
|
public function put($path, array $putData = []) |
69
|
|
|
{ |
70
|
1 |
|
return $this->request('PUT', $path, ['json' => $putData]); |
71
|
|
|
} |
72
|
|
|
|
73
|
1 |
|
public function delete($endpoint, array $data = []) |
74
|
|
|
{ |
75
|
1 |
|
throw new \BadMethodCallException("Not implemented yet"); |
76
|
|
|
} |
77
|
|
|
|
78
|
1 |
|
public function patch($endpoint, array $data = []) |
79
|
|
|
{ |
80
|
1 |
|
throw new \BadMethodCallException("Not implemented yet"); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @param string $method |
85
|
|
|
* @param string $path |
86
|
|
|
* @param array $options |
87
|
|
|
* |
88
|
|
|
* @return array |
89
|
|
|
*/ |
90
|
5 |
|
private function request($method, $path, $options) |
91
|
|
|
{ |
92
|
5 |
|
$uri = $this->endpoint . $path; |
93
|
|
|
|
94
|
5 |
|
$options = array_merge($options, $this->additionalOptions); |
95
|
|
|
|
96
|
5 |
|
$response = $this->httpClient->request($method, $uri, $options); |
97
|
|
|
|
98
|
5 |
|
return json_decode($response->getBody(), true); |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|