Add basic event system
timw4mail/php-kilo/master There was a failure building this commit Details

This commit is contained in:
Timothy Warren 2020-01-27 15:11:35 -05:00
parent 54bc83e1f9
commit f8894b971a
2 changed files with 75 additions and 0 deletions

47
src/Event.php Normal file
View File

@ -0,0 +1,47 @@
<?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.");
}
}
}

28
tests/EventTest.php Normal file
View File

@ -0,0 +1,28 @@
<?php declare(strict_types=1);
namespace Aviat\Kilo\Tests;
use Aviat\Kilo\Event;
use Aviat\Kilo\Enum\Event as EventType;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
class EventTest extends TestCase {
public function testRequiresValidEvent(): void
{
$this->expectException(InvalidArgumentException::class);
Event::bind('badEventName', fn () => null);
$this->expectException(InvalidArgumentException::class);
Event::fire('badEventName', []);
}
public function testBindAndFire(): void
{
$fn = static function($value = false) {
static::assertTrue($value);
};
Event::bind(EventType::INPUT_KEY, $fn);
Event::fire(EventType::INPUT_KEY, TRUE);
}
}