Files
server/shared/lib/Event/Event.php
T
Sebastian 62b416f13e refactor: base event
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-08-08 22:15:24 -04:00

130 lines
2.7 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 $context;
private readonly float $timestamp;
private readonly string $identifier;
public function __construct(
private readonly string $label,
array $context = [],
private readonly ?string $tenantIdentifier = null,
private readonly ?string $actorIdentity = null,
) {
self::validateContext($context);
$this->context = $context;
$this->timestamp = microtime(true);
$this->identifier = bin2hex(random_bytes(16));
}
/**
* Get the event label
*/
public function label(): string
{
return $this->label;
}
/**
* Get a context value by key
*/
public function get(string $key, mixed $default = null): mixed
{
return $this->context[$key] ?? $default;
}
/**
* Check if a context key exists
*/
public function has(string $key): bool
{
return array_key_exists($key, $this->context);
}
/**
* Get the event context
*/
public function context(): array
{
return $this->context;
}
/**
* Get all event context
*/
public function all(): array
{
return $this->context;
}
/**
* Get the event timestamp
*/
public function timestamp(): float
{
return $this->timestamp;
}
public function identifier(): string
{
return $this->identifier;
}
/**
* 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 tenantIdentifier(): ?string
{
return $this->tenantIdentifier;
}
/**
* Get the identity of the actor who triggered the event
*/
public function actorIdentity(): ?string
{
return $this->actorIdentity;
}
private static function validateContext(array $context): void
{
foreach ($context as $value) {
if (is_array($value)) {
self::validateContext($value);
continue;
}
if ($value !== null && !is_scalar($value)) {
throw new \InvalidArgumentException(
'Event context must contain only scalar, null, or array values.',
);
}
}
}
}