initial comit - too many functions

This commit is contained in:
2025-09-18 14:17:38 +02:00
parent 3043c39e5b
commit 8da012a1c4

View File

@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
final class Calco2latoApiClient
{
private string $baseUrl;
private string $apiKey;
private int $timeout;
public function __construct(string $baseUrl, string $apiKey, int $timeoutSeconds = 10)
{
$this->baseUrl = rtrim($baseUrl, '/');
$this->apiKey = $apiKey;
$this->timeout = $timeoutSeconds;
}
/**
* Low-level request wrapper (GET/POST/DELETE/PUT/PATCH).
* $query is appended to URL; $body (if provided) is JSON-encoded.
*/
private function request(string $method, string $path, array $query = [], ?array $body = null): array
{
$url = $this->baseUrl . '/' . ltrim($path, '/');
if (!empty($query)) {
$url .= (str_contains($url, '?') ? '&' : '?') . http_build_query($query);
}
$ch = curl_init($url);
$headers = [
'Accept: application/json',
'Authorization: Bearer ' . $this->apiKey,
];
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => strtoupper($method),
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => $this->timeout,
]);
if ($body !== null) {
$json = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
}
$responseBody = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($responseBody === false) {
throw new RuntimeException('cURL error: ' . $err);
}
$decoded = json_decode($responseBody, true);
if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Invalid JSON from API (HTTP ' . $status . '): ' . $responseBody);
}
if ($status < 200 || $status >= 300) {
$msg = $decoded['error'] ?? $decoded['message'] ?? 'Upstream API error';
throw new RuntimeException('API error (HTTP ' . $status . '): ' . $msg);
}
return $decoded;
}
// ---------- Airports ----------
/** Search airports by free-text (IATA/ICAO/name/city/country) */
public function searchAirports(string $q, int $limit = 20, int $offset = 0): array
{
return $this->request('GET', '/api/latest/airports/search', [
'q' => $q,
'limit' => $limit,
'offset' => $offset,
]);
}
/** Get a single airport by IATA or ICAO code */
public function getAirport(string $code): array
{
return $this->request('GET', '/api/latest/airports/' . urlencode($code));
}
// ---------- Flights ----------
/**
* Get flight estimate / emissions (example adjust to your API)
* $params might include origin, destination, date, pax, class, etc.
*/
public function flightEstimate(array $params): array
{
return $this->request('POST', '/api/latest/flights/estimate', [], $params);
}
/** Optional: resolve a route or fetch a published flight record */
public function getFlightById(string $id): array
{
return $this->request('GET', '/api/latest/flights/' . urlencode($id));
}
}