62 lines
1.6 KiB
PHP
62 lines
1.6 KiB
PHP
<?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);
|
|
}
|
|
}
|
|
|