Files
My-KOPKB/be/app/Traits/HttpClientTrait.php
T
ISMAIL MASSERAN 94ecbe5887 first init
2026-06-08 11:37:14 +08:00

105 lines
3.2 KiB
PHP

<?php
namespace App\Traits;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
trait HttpClientTrait
{
/**
* Get a configured HTTP client with global settings.
*
* @param array $additionalHeaders Additional headers to add
* @param bool $withoutVerifying Whether to skip SSL verification
* @return \Illuminate\Http\Client\PendingRequest
*/
protected function getHttpClient(array $additionalHeaders = [], bool $withoutVerifying = false)
{
$client = Http::withHeaders($additionalHeaders);
if ($withoutVerifying) {
$client = $client->withoutVerifying();
}
return $client;
}
/**
* Get a configured HTTP client with authentication.
*
* @param string $token Bearer token for authentication
* @param array $additionalHeaders Additional headers to add
* @param bool $withoutVerifying Whether to skip SSL verification
* @return \Illuminate\Http\Client\PendingRequest
*/
protected function getAuthenticatedHttpClient(string $token, array $additionalHeaders = [], bool $withoutVerifying = false)
{
$headers = array_merge([
'Authorization' => 'Bearer '.$token,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
], $additionalHeaders);
return $this->getHttpClient($headers, $withoutVerifying);
}
/**
* Log HTTP request details for debugging.
*
* @param string $method HTTP method
* @param string $url Request URL
* @param array $data Request data
* @param array $headers Request headers
*/
protected function logHttpRequest(string $method, string $url, array $data = [], array $headers = [])
{
Log::debug('HTTP Request', [
'method' => $method,
'url' => $url,
'data' => $data,
'headers' => array_keys($headers), // Don't log sensitive header values
'environment' => config('app.env'),
'proxy_enabled' => $this->isProxyEnabled(),
]);
}
/**
* Log HTTP response details for debugging.
*
* @param \Illuminate\Http\Client\Response $response
* @param string $context Additional context
*/
protected function logHttpResponse($response, string $context = '')
{
Log::debug('HTTP Response'.($context ? " - {$context}" : ''), [
'status' => $response->status(),
'successful' => $response->successful(),
'body_length' => strlen($response->body()),
'headers' => $response->headers(),
]);
}
/**
* Check if proxy is enabled for current environment.
*/
protected function isProxyEnabled(): bool
{
$config = config('http');
$proxyConfig = $config['proxy'] ?? [];
return isset($proxyConfig['enabled']) && $proxyConfig['enabled'] &&
in_array(config('app.env'), $proxyConfig['environments'] ?? []);
}
/**
* Get current proxy configuration.
*/
protected function getProxyConfig(): array
{
$config = config('http');
return $config['proxy'] ?? [];
}
}