Files
sibedas/app/ServiceClient.php

74 lines
2.0 KiB
PHP

<?php
namespace App;
use App\Helpers\ApiResponse;
use GuzzleHttp\Client;
use Exception;
class ServiceClient
{
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 = []){
try {
$headers = array_merge($this->headers, $headers);
$options = [
'headers' => $headers,
];
if ($body) {
$options['json'] = $body; // Guzzle akan mengonversi array ke JSON
}
$response = $this->client->request($method, $this->baseUrl . $url, $options);
$resultResponse = json_decode($response->getBody(), true);
return ApiResponse::successResponse($resultResponse, "Successfully fetched data");
} catch (Exception $e) {
return ApiResponse::errorResponse($e->getMessage(), $e->getCode());
}
}
// 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);
}
}