php-kilo/src/Event.php

56 lines
1.4 KiB
PHP
Raw Normal View History

2020-01-27 15:11:35 -05:00
<?php declare(strict_types=1);
namespace Aviat\Kilo;
class Event {
2020-02-05 14:50:31 -05:00
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
2020-01-27 15:11:35 -05:00
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);
}
}
}
2020-02-05 14:50:31 -05:00
public static function on(string $eventName, callable $fn): void
2020-01-27 15:11:35 -05:00
{
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
{
2020-02-05 14:50:31 -05:00
$validEvents = self::getConstList();
2020-01-27 15:11:35 -05:00
if ( ! array_key_exists($eventName, $validEvents))
{
2020-02-05 14:50:31 -05:00
throw new \InvalidArgumentException("Invalid event '{$eventName}'. Event const must exist in Aviat\\Kilo\\Event.");
2020-01-27 15:11:35 -05:00
}
}
}