pos-gis/app/Services/APIService.php

75 lines
2.0 KiB
PHP
Raw Permalink Normal View History

2024-10-07 06:13:42 +00:00
<?php
namespace App\Services;
use App\Interfaces\APIInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\RequestOptions;
class APIService extends APIInterface
{
function client(){
return new Client([
'timeout' => 60,
'connect_timeout' => 120,
'base_uri' => env("API_BASE")
]);
}
function errorAPI(RequestException $exception){
$res = new \stdClass();
$res->rc = $exception->getCode();
if ($exception instanceof BadResponseException){
$resultBody = json_decode($exception->getResponse()->getBody());
if ($resultBody == null){
$res->rm = $exception->getMessage();
return $res;
}
return $resultBody;
}elseif ($exception instanceof ConnectException){
$res->rm = $exception->getMessage();
return $res;
}else{
$res->rm = "Maintanance Server please try again later";
return $res;
}
}
function get($path, $auth = null)
{
$headers = [
'Accept' => 'application/json',
'Authorization' => $auth
];
try {
$result = $this->client()->get($path, [
RequestOptions::HEADERS => $headers
]);
return json_decode($result->getBody());
} catch (RequestException $e) {
return $this->errorAPI($e);
}
}
function post($path, $data, $auth = null)
{
$headers = [
'Accept' => 'application/json',
'Authorization' => $auth
];
try {
$result = $this->client()->post($path, [
RequestOptions::HEADERS => $headers,
RequestOptions::JSON => $data
]);
return json_decode($result->getBody());
} catch (RequestException $e) {
return $this->errorAPI($e);
}
}
}