1 | <?php |
||
9 | class Json implements JsonInterface |
||
10 | { |
||
11 | /** |
||
12 | * @var HttpClient |
||
13 | */ |
||
14 | private $httpClient; |
||
15 | |||
16 | /** |
||
17 | * @var string |
||
18 | */ |
||
19 | private $endpoint = ''; |
||
20 | |||
21 | /** |
||
22 | * @var array |
||
23 | */ |
||
24 | private $additionalOptions = []; |
||
25 | |||
26 | /** |
||
27 | * @param array $options |
||
28 | */ |
||
29 | 14 | public function __construct(array $options = []) |
|
51 | |||
52 | /** |
||
53 | * @return string |
||
54 | */ |
||
55 | 1 | public function getEndpoint() |
|
59 | |||
60 | 7 | public function get($path, array $params = [], array $options = []) |
|
61 | { |
||
62 | 7 | return $this->request('GET', $path, array_merge($options, ['query' => $params])); |
|
63 | } |
||
64 | |||
65 | 1 | public function post($path, array $postData = [], array $options = []) |
|
66 | { |
||
67 | 1 | return $this->request('POST', $path, array_merge($options, ['json' => $postData])); |
|
68 | } |
||
69 | |||
70 | 1 | public function put($path, array $putData = [], array $options = []) |
|
71 | { |
||
72 | 1 | return $this->request('PUT', $path, array_merge($options, ['json' => $putData])); |
|
73 | } |
||
74 | |||
75 | 1 | public function delete($endpoint, array $data = [], array $options = []) |
|
76 | { |
||
77 | 1 | throw new \BadMethodCallException('Not implemented yet'); |
|
78 | } |
||
79 | |||
80 | 1 | public function patch($endpoint, array $data = [], array $options = []) |
|
81 | { |
||
82 | 1 | throw new \BadMethodCallException('Not implemented yet'); |
|
83 | } |
||
84 | |||
85 | /** |
||
86 | * @param string $method |
||
87 | * @param string $path |
||
88 | * @param array $options |
||
89 | * |
||
90 | * @throws InvalidJsonResponseBodyException |
||
91 | * @throws Exception |
||
92 | * |
||
93 | * @return array |
||
94 | */ |
||
95 | 9 | protected function request($method, $path, $options) |
|
96 | { |
||
97 | try { |
||
98 | 9 | $uri = $this->endpoint . '/' . ltrim($path, '/'); |
|
99 | 9 | $options = array_merge($options, $this->additionalOptions); |
|
100 | 9 | $response = $this->httpClient->request($method, $uri, $options); |
|
101 | |||
102 | 8 | return $this->getJsonContentFromResponse($response); |
|
103 | 2 | } catch (RequestException $e) { |
|
104 | 1 | $message = $e->getMessage(); |
|
105 | 1 | $data = json_decode($e->getResponse()->getBody(), true); |
|
106 | |||
107 | 1 | if (isset($data['message'])) { |
|
108 | 1 | $message = $data['message']; |
|
109 | 1 | } |
|
110 | |||
111 | 1 | throw new Exception($message, null, $e); |
|
112 | } |
||
113 | } |
||
114 | |||
115 | /** |
||
116 | * @param ResponseInterface $response |
||
117 | * |
||
118 | * @throws InvalidJsonResponseBodyException |
||
119 | * |
||
120 | * @return array |
||
121 | */ |
||
122 | 8 | private function getJsonContentFromResponse(ResponseInterface $response) |
|
133 | } |
||
134 |