feat: make event state constructor-only and immutable
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
This commit is contained in:
+20
-30
@@ -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.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user