VitoTechnitiumDns/Services/TechnitiumClient.php
Corentin BARNICHON 0d7b62539d first commit
2026-04-16 18:13:36 +02:00

82 lines
2.1 KiB
PHP

<?php
namespace App\Vito\Plugins\LiittleCookie\VitoTechnitiumDns\Services;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
class TechnitiumClient
{
public function __construct(
private readonly string $serverUrl,
private readonly string $apiToken,
) {}
public static function fromCredentials(array $credentials): self
{
return new self(
serverUrl: rtrim($credentials['server_url'], '/'),
apiToken: $credentials['api_token'],
);
}
/**
* Perform a GET request to the Technitium API.
* The token is always appended as a query parameter.
*/
public function get(string $endpoint, array $params = []): Response
{
$params['token'] = $this->apiToken;
return $this->client()->get($this->url($endpoint), $params);
}
/**
* Perform a POST request to the Technitium API.
* The token is included in the form data.
*/
public function post(string $endpoint, array $data = []): Response
{
$data['token'] = $this->apiToken;
return $this->client()
->asForm()
->post($this->url($endpoint), $data);
}
/**
* Check if the API response indicates success.
* Technitium uses {"status": "ok"} for successful responses.
*/
public function isSuccessful(Response $response): bool
{
return $response->successful() && $response->json('status') === 'ok';
}
/**
* Extract the response payload from a Technitium API response.
* Data lives under the "response" key.
*/
public function responseData(Response $response, ?string $key = null): mixed
{
$data = $response->json('response');
if ($key !== null) {
return $data[$key] ?? null;
}
return $data;
}
private function client(): PendingRequest
{
return Http::timeout(15)->connectTimeout(5);
}
private function url(string $endpoint): string
{
return $this->serverUrl.'/api/'.ltrim($endpoint, '/');
}
}