refactor
- move elixForms API logic to specific folder - move everything else under Api folder
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
namespace Core;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
|
||||
class HttpClient {
|
||||
private $client;
|
||||
|
||||
private function client() {
|
||||
if ($this->client === null) {
|
||||
$this->client = new Client([
|
||||
'timeout' => 10.0,
|
||||
'http_errors' => false
|
||||
]);
|
||||
}
|
||||
return $this->client;
|
||||
}
|
||||
|
||||
public function get(string $url, array $headers = []) {
|
||||
return $this->request('GET', $url, null, $headers);
|
||||
}
|
||||
|
||||
public function post(string $url, $data = null, array $headers = []) {
|
||||
return $this->request('POST', $url, $data, $headers);
|
||||
}
|
||||
|
||||
private function request(string $method, string $url, $data, array $headers) {
|
||||
try {
|
||||
$options = ['headers' => $headers];
|
||||
if ($data !== null) {
|
||||
$options['json'] = $data;
|
||||
}
|
||||
|
||||
$resp = $this->client()->request($method, $url, $options);
|
||||
|
||||
$status = $resp->getStatusCode();
|
||||
$bodyRaw = $resp->getBody()->getContents();
|
||||
$contentType = $resp->getHeaderLine('Content-Type');
|
||||
|
||||
$isJson = stripos($contentType, 'application/json') !== false;
|
||||
|
||||
return [
|
||||
'status' => $status,
|
||||
'headers' => $resp->getHeaders(),
|
||||
'body' => $bodyRaw,
|
||||
'is_json' => $isJson,
|
||||
'json' => $isJson ? json_decode($bodyRaw, true) : null
|
||||
];
|
||||
|
||||
} catch (RequestException $e) {
|
||||
return [
|
||||
'status' => 500,
|
||||
'headers' => [],
|
||||
'body' => null,
|
||||
'is_json' => false,
|
||||
'json' => null,
|
||||
'error' => $e->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user