65 lines
1.7 KiB
PHP
65 lines
1.7 KiB
PHP
<?php
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
|
|
class ApiClient
|
|
{
|
|
protected string $baseUrl;
|
|
protected string $token;
|
|
|
|
public function __construct(string $baseUrl = null,string $token = null)
|
|
{
|
|
$this->baseUrl = $baseUrl;
|
|
$this->token = $token;
|
|
}
|
|
|
|
public function set(string $baseUrl = null,string $token = null):self
|
|
{
|
|
$this->baseUrl = $baseUrl;
|
|
$this->token = $token;
|
|
return $this;
|
|
}
|
|
|
|
public function setToken(string $token): self
|
|
{
|
|
$this->token = $token;
|
|
return $this;
|
|
}
|
|
|
|
public function setBaseUrl(string $url): self
|
|
{
|
|
$this->baseUrl = rtrim($url, '/');
|
|
return $this;
|
|
}
|
|
|
|
public function withDefaultHeaders(): \Illuminate\Http\Client\PendingRequest
|
|
{
|
|
return Http::withHeaders([
|
|
'Accept' => 'application/json',
|
|
'Authorization' => 'Bearer ' . $this->token,
|
|
]);
|
|
}
|
|
|
|
public function get(string $endpoint, array $query = [])
|
|
{
|
|
return $this->withDefaultHeaders()->get("{$this->baseUrl}{$endpoint}", $query);
|
|
}
|
|
|
|
public function post(string $endpoint, array $data = [])
|
|
{
|
|
return $this->withDefaultHeaders()->post("{$this->baseUrl}{$endpoint}", $data);
|
|
}
|
|
|
|
public function upload(string $endpoint, array $files = [], array $data = [])
|
|
{
|
|
$request = $this->withDefaultHeaders();
|
|
|
|
foreach ($files as $key => $filePath) {
|
|
$filename = basename($filePath);
|
|
$request = $request->attach($key, fopen($filePath, 'r'), $filename);
|
|
}
|
|
|
|
return $request->withoutVerifying()->post("{$this->baseUrl}{$endpoint}", $data);
|
|
}
|
|
} |