diff --git a/doc/01-api.md b/doc/01-api.md index 17ba333..f7098dd 100644 --- a/doc/01-api.md +++ b/doc/01-api.md @@ -66,6 +66,28 @@ $result = $a + $b; $emitter->emit('numbers_added', [$result, $a, $b]); ``` +## emit_regex($pattern, array $arguments = []) + +Emit an event, which will call all listeners by regular expression. + +Example: + +```php +$events->on('note_a1', function($channel, $velocity) { + echo "paying note a1\n"; +}); + +$events->on('note_a2', function($channel, $velocity) { + echo "paying note a2\n"; +}); + +$events->on('note_b2', function($channel, $velocity) { + echo "paying note b2\n"; +}); + +$events->emit_regex("/note_a/i", [0, 127]); +``` + ## listeners($event) Allows you to inspect the listeners attached to an event. Particularly useful diff --git a/src/EventEmitterTrait.php b/src/EventEmitterTrait.php index 1503429..63b29e8 100644 --- a/src/EventEmitterTrait.php +++ b/src/EventEmitterTrait.php @@ -138,7 +138,7 @@ public function emit($event, array $arguments = []) $onceListeners = array_values($this->onceListeners[$event]); } - if(empty($listeners) === false) { + if(empty($listeners) === false) { foreach ($listeners as $listener) { $listener(...$arguments); } @@ -151,4 +151,30 @@ public function emit($event, array $arguments = []) } } } + + public function emit_regex($pattern, array $arguments = []) + { + if ($pattern === null) { + throw new InvalidArgumentException('event name must not be null'); + } + + $listeners = []; + foreach($this->listeners as $_event => $_listeners) { + if(preg_match($pattern, $_event, $matches)) { + foreach ($_listeners as $listener) { + $listener(...$arguments); + } + } + } + + $onceListeners = []; + foreach($this->onceListeners as $_event => $_listeners) { + if(preg_match($pattern, $_event, $matches)) { + unset($this->onceListeners[$_event]); + foreach ($_listeners as $listener) { + $listener(...$arguments); + } + } + } + } }