Files
sibedas/app/Services/ServiceClient.php
2025-02-14 00:23:50 +07:00

84 lines
2.4 KiB
PHP

<?php
namespace App\Services;
use App\Traits\GlobalApiResponse;
use GuzzleHttp\Client;
use Exception;
class ServiceClient
{
use GlobalApiResponse;
private $client;
private $baseUrl;
private $headers;
/**
* Create a new class instance.
*/
public function __construct($baseUrl = '', $headers = [])
{
$this->client = new Client();
$this->baseUrl = $baseUrl;
$this->headers = array_merge(
[
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
$headers
);
}
public function makeRequest($url, $method = 'GET', $body = null, $headers = [], $timeout = 14400){
try {
$headers = array_merge($this->headers, $headers);
$options = [
'headers' => $headers,
'timeout' => $timeout,
'connect_timeout' => 60
];
if ($body) {
$options['json'] = $body; // Guzzle akan mengonversi array ke JSON
}
$response = $this->client->request($method, $this->baseUrl . $url, $options);
$responseBody = (string) $response->getBody();
if (!str_contains($response->getHeaderLine('Content-Type'), 'application/json')) {
\Log::error('Unexpected response format: ' . $responseBody);
return $this->resError('API response is not JSON');
}
$resultResponse = json_decode($responseBody, true, 512, JSON_THROW_ON_ERROR);
return $this->resSuccess($resultResponse);
} catch (Exception $e) {
\Log::error('error from client service'. $e->getMessage());
return $this->resError($e->getMessage());
}
}
// Fungsi untuk melakukan permintaan GET
public function get($url, $headers = [])
{
return $this->makeRequest($url, 'GET', null, $headers);
}
// Fungsi untuk melakukan permintaan POST
public function post($url, $body, $headers = [])
{
return $this->makeRequest($url, 'POST', $body, $headers);
}
// Fungsi untuk melakukan permintaan PUT
public function put($url, $body, $headers = [])
{
return $this->makeRequest($url, 'PUT', $body, $headers);
}
// Fungsi untuk melakukan permintaan DELETE
public function delete($url, $headers = [])
{
return $this->makeRequest($url, 'DELETE', null, $headers);
}
}