Initial commit

This commit is contained in:
2025-09-06 01:21:02 +02:00
commit 5010d085f5
6 changed files with 429 additions and 0 deletions

61
src/LogDbClient.php Normal file
View File

@@ -0,0 +1,61 @@
<?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}";
$this->sendHttp($event, $url);
break;
case 'udp':
[$ip,$port] = explode(":", $this->server, 2);
$this->sendUdp($event, $ip, $port);
break;
}
}
private function sendHttp(LogEvent $event, string $url): void
{
$message = json_encode($event);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => [
'content-type: application/json'
],
'content' => $message
]
]);
$response = file_get_contents($url, context:$context);
}
private function sendUdp(LogEvent $event, string $ip, int $port): void
{
$this->socket ??= socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$message = json_encode($event);
$len = strlen($message);
socket_sendto($this->socket, $message, $len, 0, $ip, $port);
}
}