Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
12 / 12
Event
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
3 / 3
8
100.00% covered (success)
100.00%
12 / 12
 fire
100.00% covered (success)
100.00%
1 / 1
3
100.00% covered (success)
100.00%
4 / 4
 on
100.00% covered (success)
100.00%
1 / 1
3
100.00% covered (success)
100.00%
5 / 5
 validateEvent
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
3 / 3
1<?php declare(strict_types=1);
2
3namespace Aviat\Kilo;
4
5class Event {
6    use Traits\ConstList;
7
8    // ------------------------------------------------------------------------
9    // Valid Events
10    // ------------------------------------------------------------------------
11    public const INPUT_KEY = 'INPUT_KEY';
12    public const PAGE_CHANGE = 'PAGE_CHANGE';
13    public const MOVE_CURSOR = 'MOVE_CURSOR';
14    public const QUIT_ATTEMPT = 'QUIT_ATTEMPT';
15
16    // Mapping of events to handlers
17    private static $subscribeMap = [];
18
19    public static function fire(string $eventName, $value): void
20    {
21        static::validateEvent($eventName);
22
23        if (array_key_exists($eventName, static::$subscribeMap))
24        {
25            foreach (static::$subscribeMap[$eventName] as $fn)
26            {
27                $fn($value);
28            }
29        }
30    }
31
32    public static function on(string $eventName, callable $fn): void
33    {
34        static::validateEvent($eventName);
35
36        if ( ! array_key_exists($eventName, static::$subscribeMap))
37        {
38            static::$subscribeMap[$eventName] = [];
39        }
40
41        if ( ! in_array($fn, static::$subscribeMap[$eventName], TRUE))
42        {
43            static::$subscribeMap[$eventName][] = $fn;
44        }
45    }
46
47    private static function validateEvent(string $eventName): void
48    {
49        $validEvents = self::getConstList();
50
51        if ( ! array_key_exists($eventName, $validEvents))
52        {
53            throw new \InvalidArgumentException("Invalid event '{$eventName}'. Event const must exist in Aviat\\Kilo\\Event.");
54        }
55    }
56}