Move includes to their own folder, config.php will otherwise be included and cleans up nicely
66 lines
2.1 KiB
PHP
66 lines
2.1 KiB
PHP
<?php
|
|
|
|
readonly class snips
|
|
{
|
|
public function __construct(
|
|
private string $baseUrl,
|
|
private string $apiKey,
|
|
) {}
|
|
|
|
public function getSnip(int $id): string
|
|
{
|
|
$url = $this->baseUrl . 'snip/' . $id;
|
|
$headers = [
|
|
'X-AUTH-TOKEN: ' . $this->apiKey,
|
|
'Accept: application/json',
|
|
];
|
|
|
|
$ch = curl_init($url);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
|
$response = curl_exec($ch);
|
|
curl_close($ch);
|
|
|
|
$response = $this->getResponse($response);
|
|
|
|
if (isset($response['success']) && $response['success'] === true) {
|
|
return $response['data']['content'];
|
|
} else {
|
|
throw new Exception('Error fetching snip: ' . json_encode($response));
|
|
}
|
|
// rewrite to curl
|
|
}
|
|
|
|
public function postSnip(int $id, string $content): string
|
|
{
|
|
$url = $this->baseUrl . 'snip/' . $id;
|
|
$headers = [
|
|
'X-AUTH-TOKEN: ' . $this->apiKey,
|
|
'Accept: application/json',
|
|
];
|
|
|
|
$ch = curl_init($url);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
|
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, ['content' => $content]);
|
|
$response = curl_exec($ch);
|
|
curl_close($ch);
|
|
$response = $this->getResponse($response);
|
|
|
|
if (isset($response['success']) && $response['success'] === true) {
|
|
return $response['data']['content'];
|
|
} else {
|
|
throw new Exception('Error updating snip: ' . json_encode($response));
|
|
}
|
|
}
|
|
|
|
private function getResponse(bool|string $response): array
|
|
{
|
|
$response = json_decode($response, true);
|
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
|
throw new Exception('Error decoding JSON response: ' . json_last_error_msg());
|
|
}
|
|
return $response;
|
|
}
|
|
} |