53 lines
1.3 KiB
PHP
53 lines
1.3 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Framework\Router\Result;
|
|
|
|
/**
|
|
* Repräsentiert ein einzelnes Server-Sent Event
|
|
*/
|
|
final readonly class SseEvent
|
|
{
|
|
/**
|
|
* @param string $data Der Dateninhalt des Events
|
|
* @param string|null $event Der Event-Typ (optional)
|
|
* @param string|null $id Die Event-ID (optional)
|
|
* @param int|null $retry Retry-Intervall in Millisekunden (optional)
|
|
*/
|
|
public function __construct(
|
|
public string $data,
|
|
public ?string $event = null,
|
|
public ?string $id = null,
|
|
public ?int $retry = null
|
|
) {}
|
|
|
|
/**
|
|
* Formatiert das Event in das SSE-Protokollformat
|
|
*/
|
|
public function format(): string
|
|
{
|
|
$formatted = [];
|
|
|
|
if ($this->id !== null) {
|
|
$formatted[] = "id: {$this->id}";
|
|
}
|
|
|
|
if ($this->event !== null) {
|
|
$formatted[] = "event: {$this->event}";
|
|
}
|
|
|
|
if ($this->retry !== null) {
|
|
$formatted[] = "retry: {$this->retry}";
|
|
}
|
|
|
|
// Mehrzeilige Daten unterstützen
|
|
foreach (explode("\n", $this->data) as $line) {
|
|
$formatted[] = "data: {$line}";
|
|
}
|
|
|
|
$formatted[] = ''; // Leere Zeile am Ende
|
|
|
|
return implode("\n", $formatted);
|
|
}
|
|
}
|