47 lines
1.0 KiB
PHP
47 lines
1.0 KiB
PHP
|
<?php declare(strict_types=1);
|
||
|
|
||
|
namespace Aviat\Kilo;
|
||
|
|
||
|
use Aviat\Kilo\Enum\Event as EventEnum;
|
||
|
|
||
|
class Event {
|
||
|
private static $subscribeMap = [];
|
||
|
|
||
|
public static function fire(string $eventName, $value): void
|
||
|
{
|
||
|
static::validateEvent($eventName);
|
||
|
|
||
|
if (array_key_exists($eventName, static::$subscribeMap))
|
||
|
{
|
||
|
foreach (static::$subscribeMap[$eventName] as $fn)
|
||
|
{
|
||
|
$fn($value);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static function bind(string $eventName, callable $fn): void
|
||
|
{
|
||
|
static::validateEvent($eventName);
|
||
|
|
||
|
if ( ! array_key_exists($eventName, static::$subscribeMap))
|
||
|
{
|
||
|
static::$subscribeMap[$eventName] = [];
|
||
|
}
|
||
|
|
||
|
if ( ! in_array($fn, static::$subscribeMap[$eventName], TRUE))
|
||
|
{
|
||
|
static::$subscribeMap[$eventName][] = $fn;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private static function validateEvent(string $eventName): void
|
||
|
{
|
||
|
$validEvents = EventEnum::getConstList();
|
||
|
|
||
|
if ( ! array_key_exists($eventName, $validEvents))
|
||
|
{
|
||
|
throw new \InvalidArgumentException("Invalid event '{$eventName}'. Event const must exist in Aviat\\Kilo\\Enum\\Event.");
|
||
|
}
|
||
|
}
|
||
|
}
|