coryd.dev/api/Classes/ApiHandler.php

72 lines
1.7 KiB
PHP

<?php
namespace App\Classes;
use GuzzleHttp\Client;
require __DIR__ . "/../../vendor/autoload.php";
abstract class ApiHandler
{
protected string $postgrestUrl;
protected string $postgrestApiKey;
public function __construct()
{
$this->loadEnvironment();
}
private function loadEnvironment(): void
{
$this->postgrestUrl =
$_ENV["POSTGREST_URL"] ?? getenv("POSTGREST_URL") ?: "";
$this->postgrestApiKey =
$_ENV["POSTGREST_API_KEY"] ?? getenv("POSTGREST_API_KEY") ?: "";
}
protected function ensureCliAccess(): void
{
if (php_sapi_name() !== "cli" && $_SERVER["REQUEST_METHOD"] !== "POST") {
$this->redirectNotFound();
}
}
protected function redirectNotFound(): void
{
header("Location: /404", true, 302);
exit();
}
protected function fetchFromPostgREST(
string $endpoint,
string $query = "",
string $method = "GET",
?array $body = null
): array {
$url = "{$this->postgrestUrl}/{$endpoint}?{$query}";
$options = [
"headers" => [
"Content-Type" => "application/json",
"Authorization" => "Bearer {$this->postgrestApiKey}",
],
];
if ($method === "POST" && $body) $options["json"] = $body;
$response = (new Client())->request($method, $url, $options);
return json_decode($response->getBody(), true) ?? [];
}
protected function sendResponse(string $message, int $statusCode): void
{
http_response_code($statusCode);
header("Content-Type: application/json");
echo json_encode(["message" => $message]);
exit();
}
protected function sendErrorResponse(string $message, int $statusCode): void
{
$this->sendResponse($message, $statusCode);
}
}