Files
client-php/src/LogDbClient.php

79 lines
2.2 KiB
PHP
Raw Normal View History

2025-09-06 01:21:02 +02:00
<?php
namespace LogDb\Client;
class LogDbClient
{
private mixed $socket = null;
public function __destruct()
{
if (\is_resource($this->socket)) socket_close($this->socket);
}
public function __construct(
private readonly string $server,
private readonly string $type = 'http'
)
{
}
public function logEvent(LogEvent $event): void
{
switch ($this->type) {
case 'http':
$url = $this->server . "/api/logdb/v1/create-event";
if (!str_starts_with($url, "http")) $url = "http://{$url}";
2025-09-06 01:35:04 +02:00
$this->sendHttp(json_encode($event), $url);
2025-09-06 01:21:02 +02:00
break;
case 'udp':
[$ip,$port] = explode(":", $this->server, 2);
2025-09-06 01:35:04 +02:00
$this->sendUdp(json_encode($event), $ip, $port);
2025-09-06 01:21:02 +02:00
break;
}
}
2025-09-06 01:35:04 +02:00
public function logEventBatch(array $events): void
{
switch ($this->type) {
case 'http':
$url = $this->server . "/api/logdb/v1/create-event";
if (!str_starts_with($url, "http")) $url = "http://{$url}";
$this->sendHttp(json_encode($event), $url);
break;
case 'udp':
foreach ($events as $event) {
if ($event instanceof LogEvent) {
[$ip,$port] = explode(":", $this->server, 2);
$this->sendUdp(json_encode($event), $ip, $port);
}
}
break;
}
}
private function sendHttp(string $message, string $url): void
2025-09-06 01:21:02 +02:00
{
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => [
'content-type: application/json'
],
'content' => $message
]
]);
$response = file_get_contents($url, context:$context);
}
2025-09-06 01:35:04 +02:00
private function sendUdp(string $message, string $ip, int $port): void
2025-09-06 01:21:02 +02:00
{
$this->socket ??= socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$len = strlen($message);
socket_sendto($this->socket, $message, $len, 0, $ip, $port);
}
}