feat: make event state constructor-only and immutable

Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
This commit is contained in:
2026-08-05 22:46:33 -04:00
parent ba4deccea9
commit 52afd35d6f
8 changed files with 266 additions and 193 deletions
+20 -30
View File
@@ -10,16 +10,18 @@ namespace KTXF\Event;
class Event
{
private bool $propagationStopped = false;
private array $data = [];
private float $timestamp;
private string $eventId;
private ?string $tenantId = null;
private ?string $identityId = null;
private readonly array $data;
private readonly float $timestamp;
private readonly string $eventId;
public function __construct(
private readonly string $name,
array $data = []
array $data = [],
private readonly ?string $tenantId = null,
private readonly ?string $identityId = null,
) {
self::validateData($data);
$this->data = $data;
$this->timestamp = microtime(true);
$this->eventId = bin2hex(random_bytes(16));
@@ -41,15 +43,6 @@ class Event
return $this->data[$key] ?? $default;
}
/**
* Set a data value
*/
public function set(string $key, mixed $value): self
{
$this->data[$key] = $value;
return $this;
}
/**
* Check if a data key exists
*/
@@ -111,15 +104,6 @@ class Event
return $this->tenantId;
}
/**
* Set tenant ID for multi-tenant context
*/
public function setTenantId(?string $tenantId): self
{
$this->tenantId = $tenantId;
return $this;
}
/**
* Get identity ID (user who triggered the event)
*/
@@ -128,12 +112,18 @@ class Event
return $this->identityId;
}
/**
* Set identity ID
*/
public function setIdentityId(?string $identityId): self
private static function validateData(array $data): void
{
$this->identityId = $identityId;
return $this;
foreach ($data as $value) {
if (is_array($value)) {
self::validateData($value);
continue;
}
if ($value !== null && !is_scalar($value)) {
throw new \InvalidArgumentException(
'Event data must contain only scalar, null, or array values.',
);
}
}
}
}