php-kilo/src/Event.php

56 lines
1.4 KiB
PHP

<?php declare(strict_types=1);
namespace Aviat\Kilo;
class Event {
use Traits\ConstList;
// ------------------------------------------------------------------------
// Valid Events
// ------------------------------------------------------------------------
public const INPUT_KEY = 'INPUT_KEY';
public const PAGE_CHANGE = 'PAGE_CHANGE';
public const MOVE_CURSOR = 'MOVE_CURSOR';
public const QUIT_ATTEMPT = 'QUIT_ATTEMPT';
// Mapping of events to handlers
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 on(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 = self::getConstList();
if ( ! array_key_exists($eventName, $validEvents))
{
throw new \InvalidArgumentException("Invalid event '{$eventName}'. Event const must exist in Aviat\\Kilo\\Event.");
}
}
}