Files
server/shared/lib/Event/Event.php
T
2026-08-05 22:46:33 -04:00

130 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace KTXF\Event;
/**
* Base event class for the event bus system
*/
class Event
{
private bool $propagationStopped = false;
private readonly array $data;
private readonly float $timestamp;
private readonly string $eventId;
public function __construct(
private readonly string $name,
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));
}
/**
* Get the event name
*/
public function getName(): string
{
return $this->name;
}
/**
* Get a data value by key
*/
public function get(string $key, mixed $default = null): mixed
{
return $this->data[$key] ?? $default;
}
/**
* Check if a data key exists
*/
public function has(string $key): bool
{
return array_key_exists($key, $this->data);
}
/**
* Get all data
*/
public function getData(): array
{
return $this->data;
}
/**
* Alias for getData() for backward compatibility
*/
public function all(): array
{
return $this->data;
}
/**
* Get the event timestamp
*/
public function getTimestamp(): float
{
return $this->timestamp;
}
public function getEventId(): string
{
return $this->eventId;
}
/**
* Stop event propagation to subsequent listeners
*/
public function stopPropagation(): void
{
$this->propagationStopped = true;
}
/**
* Check if propagation is stopped
*/
public function isPropagationStopped(): bool
{
return $this->propagationStopped;
}
/**
* Get tenant ID for multi-tenant context
*/
public function getTenantId(): ?string
{
return $this->tenantId;
}
/**
* Get identity ID (user who triggered the event)
*/
public function getIdentityId(): ?string
{
return $this->identityId;
}
private static function validateData(array $data): void
{
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.',
);
}
}
}
}