coryd.dev/app/Classes/BaseHandler.php

106 lines
3 KiB
PHP

<?php
namespace App\Classes;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
abstract class BaseHandler
{
protected string $postgrestUrl;
protected string $postgrestApiKey;
protected ?\Redis $cache = null;
public function __construct()
{
$this->loadEnvironment();
$this->initializeCache();
}
private function loadEnvironment(): void
{
$this->postgrestUrl = $_ENV['POSTGREST_URL'] ?? getenv('POSTGREST_URL') ?? '';
$this->postgrestApiKey = $_ENV['POSTGREST_API_KEY'] ?? getenv('POSTGREST_API_KEY') ?? '';
}
protected function initializeCache(): void
{
if (class_exists('Redis')) {
try {
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$this->cache = $redis;
} catch (\Exception $e) {
error_log('Redis connection failed: '.$e->getMessage());
$this->cache = null;
}
} else {
error_log('Redis extension not found — caching disabled.');
$this->cache = null;
}
}
protected function makeRequest(string $method, string $endpoint, array $options = []): array
{
$client = new Client();
$url = rtrim($this->postgrestUrl, '/').'/'.ltrim($endpoint, '/');
try {
$response = $client->request($method, $url, array_merge_recursive([
'headers' => [
'Authorization' => "Bearer {$this->postgrestApiKey}",
'Content-Type' => 'application/json',
],
], $options));
$responseBody = $response->getBody()->getContents();
if (empty($responseBody)) {
return [];
}
$data = json_decode($responseBody, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \Exception('Invalid JSON: '.json_last_error_msg());
}
return $data;
} catch (RequestException $e) {
$response = $e->getResponse();
$statusCode = $response ? $response->getStatusCode() : 'N/A';
$responseBody = $response ? $response->getBody()->getContents() : 'No response';
throw new \Exception("HTTP {$method} {$url} failed with status {$statusCode}: {$responseBody}");
} catch (\Exception $e) {
throw new \Exception('Request error: '.$e->getMessage());
}
}
protected function fetchFromApi(string $endpoint, string $query = ''): array
{
$url = $endpoint.($query ? "?{$query}" : '');
return $this->makeRequest('GET', $url);
}
protected function sendResponse(array $data, int $statusCode = 200): void
{
http_response_code($statusCode);
header('Content-Type: application/json');
echo json_encode($data);
exit();
}
protected function sendErrorResponse(string $message, int $statusCode = 500): void
{
$this->sendResponse(['error' => $message], $statusCode);
}
}